﻿// 2013年7月21日4:10:29
// 漠然
// 主要类 是用于控制游戏实现自动化的核心类库
using Mrsoft.Common;
using Mrsoft.Model;
using Mrsoft.UI;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;


namespace Mrsoft.Core
{
    partial class DirectDealGame
    {

        //线程控制资源管理器
        public ThreadControler Controler = new ThreadControler();
        private readonly int dwProcessId;
        private XY _tarXy;
        public static GameData Data = null;
        public bool CoreClosingControler;       //对象主要控制器 当它为真的时候表示对象已经处于关闭状态 默认值为假
        public Gamer TheGamer;                  //角色的实时状态
        public MenPai TheMenPai;                //角色所属的门派和关联关键信息
        public GamerConfig Conf;                //配置对象
        public KillMonsterData KillMonData;     //杀怪的技能和挂机点
        private DmLibary dm;                    //大漠组件
        public Process TheGameProcess;          //游戏客户端进程
        private ThreadMethods nowWorkingMethod; //跟踪运行信息
        public BaitanConfig BaitanConf { private set; get; }


        #region 事件接口
        //委托声明
        public delegate void LsStateChange(int dwProcessId, string stateMsg, int index);
        public delegate void QuitEventHandle(int dwProcessId);
        public delegate void SetShow(DirectDealGame core);

        //事件申明
        public static event SetShow SetShowEvent;
        public static event LsStateChange LsStateChangeEvent;
        public static event QuitEventHandle QuitEvent;

        private void WorkStateShow(GameState stateMsg = GameState.空闲) {
            if (LsStateChangeEvent != null)
                LsStateChangeEvent(dwProcessId, stateMsg.ToString(), 2);
        }
        #endregion

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="temGame">游戏客户端进程组件</param>
        /// <param name="temName"></param>
        public DirectDealGame(Process temGame, string temName) {
            TheGameProcess = temGame;
            dwProcessId = temGame.Id;
            //初始化配置实例 具体配置加载由Init()执行
            Conf = new GamerConfig();
            //初始化用于保存当前角色状态的实例
            TheGamer = new Gamer();
            //开启后台线程监视运行
            new Task(GameWathcer, temName).Start();
        }

        #region 主线任务管理

        /// <summary>
        /// 角色主任务线程
        /// </summary>
        private Task mainThread;

        /// <summary>
        /// 主线程任务启动器
        /// </summary>
        /// <param name="wantedAction">要创建的任务的名字</param>
        /// <param name="arg">传入的要创建任务的参数</param>
        /// <param name="noCheck">用于区分是用户操作的创建任务还是自动创建的</param>
        public void TaskStartManger(ThreadMethods wantedAction, object arg = null) {
            if (mainThread == null || mainThread.IsCompleted) {
                BuildTask(wantedAction, arg);
            }
            else if (wantedAction != this.nowWorkingMethod) {
                string strMsg = string.Format("[{0}]运行中呢！如果要执行[{1}]请先停止当前工作!", this.nowWorkingMethod, wantedAction);
                MsgListener.MsgBoxMsgShow(strMsg, "任务冲突");
            }
        }

        /// <summary>
        /// 创建主线任务
        /// </summary>
        /// <param name="method"></param>
        /// <param name="arg"></param>
        private void BuildTask(ThreadMethods method, object arg) {

            switch (method) {
                case ThreadMethods.采集:
                    SetMainThread(CaiJiMainThread);
                    break;
                case ThreadMethods.炼金:
                    SetMainThread(LianJinThread);
                    break;
                case ThreadMethods.加工:
                    SetMainThread(CaiLiaoJiaGongThread, arg);
                    break;
                case ThreadMethods.挂机:
                    SetMainThread(GuaJiThread);
                    break;
                case ThreadMethods.箱子棋局:
                    SetMainThread(XiangZiQiJuThread);
                    break;
                case ThreadMethods.和尚反贼:
                    SetMainThread(HsFzThread);
                    break;
                case ThreadMethods.钓鱼:
                    SetMainThread(DyThread);
                    break;
                case ThreadMethods.许愿:
                    SetMainThread(XuYuanThreadFunc);
                    break;
                case ThreadMethods.圣兽山:
                    SetMainThread(PigThread);
                    break;
                case ThreadMethods.收元宝:
                    SetMainThread(ShouYbThread);
                    break;
                case ThreadMethods.种植:
                    SetMainThread(ZhongZhiThread);
                    break;
                case ThreadMethods.打图:
                    SetMainThread(AutoDatu);
                    break;
                case ThreadMethods.开图:
                    SetMainThread(Kt);
                    break;
                case ThreadMethods.四绝:
                    SetMainThread(SiJueZhuangThread);
                    break;
                case ThreadMethods.摆摊:
                    SetMainThread(Baitan);
                    break;
                case ThreadMethods.收摊:
                    SetMainThread(ShouTan);
                    break;
                case ThreadMethods.帮会宝盆:
                    SetMainThread(BaoPen);
                    break;
                case ThreadMethods.楼兰幻境:
                    SetMainThread(LoulanLinPai);
                    break;
            }
            if (mainThread != null) {
                this.nowWorkingMethod = method;
                mainThread.Start();
                mainThread.ContinueWith(t => {
                    if (mainThread.IsFaulted) {
                        WorkStateShow(GameState.空闲);
                        SendMessageToUi(string.Format("[线程异常]：{0}{1}", mainThread.Exception.Message, mainThread.Exception.StackTrace));
                    }
                });
            }
        }

        /// <summary>
        /// 创建没有参数的主线程
        /// </summary>
        /// <param name="action"></param>
        private void SetMainThread(Action action) {
            mainThread = new Task(action);
        }

        /// <summary>
        /// 创建待有参数的主线程
        /// </summary>
        /// <param name="function"></param>
        /// <param name="args"></param>
        private void SetMainThread(Action<object> function, object args) {
            mainThread = new Task(function, args);
        }
        #endregion

        #region 材料加工
        private void CaiLiaoJiaGongThread(object obj) {
            var theType = (CaiLiaoJiaGongType)obj;
            Controler.JGControler = true;
            WorkStateShow(GameState.加工);
            int maxTry = 3;
            while (Controler.JGControler && !CoreClosingControler && maxTry > 0) {

                if (TheGamer.JsStaticCounter > 0) {
                    CailiaoJg((int)theType);
                    for (int i = 0; i < 10; i++) {
                        Thread.Sleep(100);
                        if (TheGamer.State == 8) {
                            maxTry = 3;
                            break;
                        }
                    }
                    if (TheGamer.JsStaticCounter > 0)
                        maxTry--;
                }
                Thread.Sleep(100);
            }
            WorkStateShow(GameState.空闲);
        }
        #endregion

        #region 角色监视器

        /// <summary>
        /// 当前角色的名字
        /// </summary>
        public string PermaName { private set; get; }

        /// <summary>
        /// 角色状态监视线程
        /// </summary>
        /// <param name="temName"></param>
        private void GameWathcer(object temName) {
            int maxtry = 2;
        re:
            try {
                xiao = new xiao.Core();
            }
            catch {
                NativeMethods.ComRegister(Path.Combine(Directory.GetCurrentDirectory(), @"插件\xiao.dll"));
                if (maxtry-- > 0)
                    goto re;
                MsgListener.MsgBoxMsgShow("重要插件未能启动", "插件错误");
                return;
            }

            while (!CoreClosingControler && gameHwnd == 0) {
                gameHwnd = xiao.BindWindow(dwProcessId);
                Thread.Sleep(100);
            }
            //初始化大漠组件
            dm = new DmLibary(gameHwnd);
            //直接加载配置文件
            LoadConfig(temName as string);
            //配置加载完成之后运行保护线程
            new Task(Protecter).Start();
            //记录当前的地图 用于和实时数据比较判定地图是否发生了变化
            var foreMap = string.Empty;
            //临时宠物ID
            var temPetIndex = 0;
            WorkStateShow(GameState.空闲);

            if (SetShowEvent != null)
                SetShowEvent(this);

            while (!CoreClosingControler) {
                Thread.Sleep(100);

                #region 检查到游戏退出了执行当前实例的销毁工作
                if (TheGameProcess.HasExited) {
                    Close();
                    if (QuitEvent != null) {
                        QuitEvent(dwProcessId);
                    }
                    continue;
                }
                #endregion

                #region 答题检测和处理
                if (NativeMethods.Ri(dwProcessId, Data.FLAG_QUESTION, Data.FLAG_OFF_1, Data.FLAG_OFF_2, Data.FLAG_OFF_3) == 1) {
                    TheGamer.Dati = true;
                    if (!Controler.DtControler) {
                        TheGamer.DatiTime = DateTime.Now;
                        Controler.DtControler = true;
                        new Task(AnswerQuestion).Start();
                    }
                }
                else {
                    TheGamer.Dati = false;
                }
                #endregion

                TheGamer.Name = NativeMethods.Rs(dwProcessId, Data.JS, Data.JS_OFF_1, Data.JS_OFF_2, Data.JS_OFF_3, Data.JS_NAME);
                //检查到地图出现了转换
                TheGamer.MapName = NativeMethods.Rs(dwProcessId, Data.MAP, Data.MAP_OFF_1, Data.MAP_OFF_2);
                if (TheGamer.MapName != foreMap) {
                    TheGamer.MapChangeCounter = 0;
                    foreMap = TheGamer.MapName;
                    continue;
                }

                TheGamer.MapChangeCounter++;
                //人物相关信息一级偏移地址
                var rwObject1 = NativeMethods.Ri(dwProcessId, Data.JS, Data.JS_OFF_1);
                //人物相关信息三级偏移地址
                var rwObject3 = NativeMethods.Ri(dwProcessId, rwObject1 + Data.JS_OFF_2, Data.JS_OFF_3);
                TheGamer.HP = NativeMethods.Ri(dwProcessId, rwObject3 + Data.JS_HP);
                TheGamer.State = NativeMethods.Ri(dwProcessId, rwObject1 + Data.JS_STATE);

                if (TheGamer.HP < 1 || TheGamer.State < 0) {
                    TheGamer.MapChangeCounter = TheGamer.JsStaticCounter = 0;
                    continue;
                }

                if (PermaName != TheGamer.Name && !string.IsNullOrEmpty(TheGamer.Name) && TheGamer.MapChangeCounter > 20) {
                    LoadConfig(TheGamer.Name);
                }

                if (TheGamer.State == 0)
                    TheGamer.JsStaticCounter++;
                else
                    TheGamer.JsStaticCounter = 0;

                TheGamer.Energy = NativeMethods.Ri(dwProcessId, rwObject3 + Data.JS_ENERGY);
                TheGamer.EnergyMax = NativeMethods.Ri(dwProcessId, rwObject3 + Data.JS_ENERGY + 4);

                TheGamer.JsXY.X = NativeMethods.Rf(dwProcessId, rwObject1 + Data.JS_X);
                TheGamer.JsXY.Y = NativeMethods.Rf(dwProcessId, rwObject1 + Data.JS_Y);

                TheGamer.MP = NativeMethods.Ri(dwProcessId, rwObject3 + Data.JS_MP);
                TheGamer.Ex = NativeMethods.Ri(dwProcessId, rwObject3 + Data.JS_EX);
                TheGamer.Level = NativeMethods.Ri(dwProcessId, rwObject3 + Data.JS_HP);
                TheGamer.HPMax = NativeMethods.Ri(dwProcessId, rwObject3 + Data.JS_HP_MAX);
                TheGamer.MPMax = NativeMethods.Ri(dwProcessId, rwObject3 + Data.JS_MP_MAX);
                TheGamer.MonKilled = NativeMethods.Ri(dwProcessId, rwObject3 + Data.JS_COUNT_KILL);

                TheGamer.Horse = NativeMethods.Ri(dwProcessId, rwObject3 + Data.JS_HORSE) != 1;

                #region 宠物数据读取
                var temPetId = NativeMethods.Ri(dwProcessId, rwObject3 + Data.JS_PET_ID);
                var petObjet = NativeMethods.Ri(dwProcessId, Data.PET, Data.PET_OFF);
                if (temPetId != NativeMethods.Ri(dwProcessId, petObjet + Data.PET_ID + Data.PET_LENGTH * temPetIndex)) {
                    for (temPetIndex = 0; temPetIndex < 10; temPetIndex++) {
                        if (NativeMethods.Ri(dwProcessId, petObjet + Data.PET_ID + Data.PET_LENGTH * temPetIndex) == temPetId)
                            break;
                    }
                }

                //宠物数据不存在 那么表示没有宠物出战
                if (temPetIndex > 9) {
                    if (!string.IsNullOrEmpty(TheGamer.PetName))
                        TheGamer.PetName = "";
                    TheGamer.PetHappy = TheGamer.PetHP = TheGamer.PetHPMax = TheGamer.PetLevel = -1;
                    continue;
                }

                TheGamer.PetHP = NativeMethods.Ri(dwProcessId, petObjet + Data.PET_HP + Data.PET_LENGTH * temPetIndex);
                TheGamer.PetName = NativeMethods.Rs(dwProcessId, petObjet + Data.PET_NAME + Data.PET_LENGTH * temPetIndex);
                TheGamer.PetHappy = NativeMethods.Ri(dwProcessId, petObjet + Data.PET_HAPPY + Data.PET_LENGTH * temPetIndex);
                TheGamer.PetLevel = NativeMethods.Ri(dwProcessId, petObjet + Data.PET_LEVEL + Data.PET_LENGTH * temPetIndex);
                TheGamer.PetHPMax = NativeMethods.Ri(dwProcessId, petObjet + Data.PET_HP_MAX + Data.PET_LENGTH * temPetIndex);
                #endregion
            }
        }

        /// <summary>
        /// 角色状态保护线程
        /// </summary>
        private void Protecter() {
            int temValue = 0;
            //string[] NoDealMaps = { "燕子坞", "四绝庄", "飘渺峰", "兵圣奇阵", "生死擂台", "圣兽山副本" };
            //string CQStr = "出窍";
            //string CQColor = "fdeb78-02ffff|bbbbbb-02ffff";

            var npc = new Monster();

            while (!CoreClosingControler) {
                Thread.Sleep(200);
                if (string.IsNullOrEmpty(PermaName) || string.IsNullOrEmpty(TheGamer.Name))
                    continue;
                //if (theGamer.State == 9)
                //{
                //    #region 出窍处理
                //    if (cfg.mbHell.Value && !NoDealMaps.Contains(theGamer.MapName))
                //    {
                //        int x, y, width, height;
                //        if (dm.GetClientSize(out width, out height)
                //            && dm.DmRcWord(CQStr, CQColor, out x, out y, 0, 50, width, height))
                //        {
                //            this.dm.DmClick(x + 14, y + 7, 1, true);
                //            Thread.Sleep(1000);
                //        }
                //        Thread.Sleep(1000);
                //    }
                //    #endregion
                //}
                //else 
                if (TheGamer.MapName == "地府") {
                    #region 死亡处理
                    if (Conf.mbHell.Value) {
                        MsgListener.CommonMsgShow(PermaName, "地府处理……");
                        if (GetNpc("孟婆", ref npc)) {
                            WalkToXy(npc.MonXy);
                            Thread.Sleep(1000);
                            if (npc.MonXy.HowFar(TheGamer.JsXY) < 2 &&
                                TalkNpc(npc.ID, Conf.msHell.Value)) {
                                for (int i = 0; i < 10; i++) {
                                    Thread.Sleep(1000);
                                    if (TheGamer.MapName != "地府")
                                        break;
                                }
                            }
                        }
                    }
                    #endregion
                }
                else if (TheGamer.MapName == "监狱") {
                    #region 监狱处理
                    if (Conf.mbJail.Value) {
                        Conf.msJail.Value = Conf.msJail.Value ?? "洛阳";
                        if (TheGamer.JsXY.HowFar(44, 31) > 5) {
                            MsgListener.CommonMsgShow(PermaName, "监狱处理");
                            WalkToXy(44f, 31f);
                        }
                        else if (GetNpc("张正贵", ref npc)) {
                            WalkToXy(npc.MonXy);
                            Thread.Sleep(200);
                            if (Controler.PsControler) {
                                TalkNpc(npc.ID, "FWGDT_090428");
                                Thread.Sleep(1500);
                                TalkNpc("INTERFACE_XML_557");
                                Thread.Sleep(2000);
                            }
                            TalkNpc(npc.ID, "我要出去");
                            Thread.Sleep(2000);
                            if (TalkNpc(Conf.msJail.Value))
                                Thread.Sleep(5000);
                            Thread.Sleep(1000);
                        }
                    }
                    #endregion
                }
                else if (!TheGamer.Horse) {
                    //正常
                    if (!string.IsNullOrEmpty(TheGamer.PetName)) {
                        #region 宠物HP
                        if (Conf.mbPetHP.Value && !string.IsNullOrEmpty(Conf.msPetHP.Value) && TheGamer.PetHPMax * Conf.miPetHP.Value / 100 > TheGamer.PetHP) {
                            for (int i = 0; i < 10; i++) {
                                Thread.Sleep(200);
                                if (i % 5 == 0) {
                                    temValue = TheGamer.PetHP;
                                    dm.KeyPressChar(Conf.msPetHP.Value);
                                }
                                else if (temValue != TheGamer.PetHP) {
                                    break;
                                }
                            }
                        }
                        #endregion
                        #region 宠物HAPPY
                        if (Conf.miPetHappy.Value >= TheGamer.PetHappy && !string.IsNullOrEmpty(Conf.msPetHappy.Value)) {
                            for (int i = 0; i < 10; i++) {
                                Thread.Sleep(200);
                                if (i % 5 == 0) {
                                    temValue = TheGamer.PetHappy;
                                    dm.KeyPressChar(Conf.msPetHappy.Value);
                                }
                                else if (temValue != TheGamer.PetHappy) {
                                    break;
                                }
                            }
                        }
                        #endregion
                    }
                    #region 人物MP
                    if (Conf.mbJsMP.Value && !string.IsNullOrEmpty(Conf.msJsMP.Value) && TheGamer.MPMax * Conf.miJsMP.Value / 100 > TheGamer.MP) {
                        for (int i = 0; i < 10; i++) {
                            Thread.Sleep(200);
                            if (i % 5 == 0) {
                                temValue = TheGamer.MP;
                                dm.KeyPressChar(Conf.msJsMP.Value);
                            }
                            else if (temValue != TheGamer.MP) {
                                break;
                            }
                        }
                    }
                    #endregion
                    #region 人物HP
                    if (Conf.mbJsHP.Value && !string.IsNullOrEmpty(Conf.msJsHP.Value) && TheGamer.HPMax * Conf.miJsHP.Value / 100 > TheGamer.HP) {
                        for (int i = 0; i < 10; i++) {
                            Thread.Sleep(200);
                            if (i % 5 == 0) {
                                temValue = TheGamer.HP;
                                dm.KeyPressChar(Conf.msJsHP.Value);
                            }
                            else if (temValue != TheGamer.HP) {
                                break;
                            }
                        }
                    }
                    #endregion
                }
            }
        }

        /// <summary>
        /// 自动答题线程
        /// </summary>
        private void AnswerQuestion() {
            //答题状态
            if (!DatiManager.HuiYanDati && !DatiManager.LocalDati)
                NativeMethods.FlashWindow((IntPtr)gameHwnd, false);
            while (Controler.DtControler && !CoreClosingControler) {
                if (!DatiManager.HuiYanDati && !DatiManager.LocalDati) {
                    if (FrmMain.AlarmMusicFile.Value == "NULL" || !File.Exists(FrmMain.AlarmMusicFile.Value)) {
                        Console.Beep();
                        Thread.Sleep(500);
                    }
                    else {
                        int musicId = dm.Play(FrmMain.AlarmMusicFile.Value);
                        while (!CoreClosingControler && TheGamer.Dati && !DatiManager.HuiYanDati && !DatiManager.LocalDati) {
                            Thread.Sleep(200);
                        }
                        dm.Stop(musicId);
                    }
                }
                else {
                    if (dm.GetWindowState(3) == 1) {
                        dm.SetWindowState(12);
                        Thread.Sleep(200);
                    }
                    string imagePath = string.Format(@"{0}\user\答题图片\", Directory.GetCurrentDirectory());
                    string imageName = string.Format("{2}{0}@{1}.jpg", PermaName, DateTime.Now.ToBinary(), imagePath);
                    if (!Directory.Exists(imagePath)) {
                        Directory.CreateDirectory(imagePath);
                    }
                    const string str = "验证码识别";
                    const string color = "fff263-0fffff";
                    int dwX, dwY;
                    if (dm.DmRcWord(str, color, out dwX, out dwY)) {
                        int dtX, dtY;
                        int theAnswer = 0;
                        if (dm.CaptureJpg(dwX + 27, dwY + 30, dwX + 27 + 165, dwY + 32 + 165, imageName, 80) &&
                            dm.DmRcWord(str, color, out dtX, out dtY) &&
                             dwX == dtX &&
                             dwY == dtY
                            ) {

                            var datiModel = new DatiModel() {
                                Timeout = 50,
                                ImageFullPath = imageName,
                                QuestinType = 8000,
                                TipsMessage = "返回1234"
                            };

                            var res = DatiManager.Answer(datiModel);

                            if (!res.OK || string.IsNullOrEmpty(res.Message) || res.Message.Length > 1) {
                                SendMessageToUi("答题失败," + res.Message);
                                var r = new Random();
                                theAnswer = r.Next(1, 4);
                            }
                            else {
                                theAnswer = int.Parse(res.Message);
                            }

                            #region 游戏答题
                            NativeMethods.IniWriteValue("./user/答案记录.ini", "答题信息", imageName, theAnswer.ToString(CultureInfo.InvariantCulture));
                            //记录答案
                            if (theAnswer > 0) {
                                lock (dm) {
                                    while (TheGamer.Dati) {
                                        if (dm.DmRcWord(str, color, out dwX, out dwY)) {
                                            dm.DmClick(dwX + 110, dwY + 121 + (theAnswer - 1) * 25, 5);
                                            dm.DmClick(dwX + 200, dwY + 214);
                                            Thread.Sleep(500);
                                            if (TheGamer.Dati) {
                                                dm.DmClick(-1, -1);
                                            }
                                        }
                                        Thread.Sleep(1000);
                                    }
                                }
                            }
                            #endregion

                            if (File.Exists(imageName))
                                File.Delete(imageName);
                        }
                    }
                }
                if (!TheGamer.Dati)
                    break;
            }
            Controler.DtControler = false;
        }

        /// <summary>
        /// 角色配置加载
        /// </summary>
        /// <param name="user"></param>
        private void LoadConfig(string user) {
            //配置文件加载
            var path = "./user/";
            var configFileName = string.Format("{0}{1}.cfg", path, user);
            var kmDataFileName = string.Format("{0}{1}.xml", path, user);

            lock (Conf) {
                Conf.Init(configFileName);
                TheZhongZhiInfo = ZhongZhiInfo.FromXml(user);
                KillMonData = KillMonsterData.Create(kmDataFileName);
                BaitanConf = BaitanConfig.Create(user);
            }

            GetMenPai(user);
            MsgListener.CommonMsgShow(user, TheMenPai.MyMenPai.ToString());
            image = null;
            PermaName = user;
            CpuDown();
            NativeMethods.SetWindowTextA((IntPtr)gameHwnd, PermaName);
            //通知修改状态和重载配置文件
            if (LsStateChangeEvent != null)
                LsStateChangeEvent(dwProcessId, PermaName, 1);
        }

        /// <summary>
        /// 获取角色门派
        /// </summary>
        /// <param name="name"></param>
        private void GetMenPai(string name) {
            if (string.IsNullOrEmpty(name))
                return;
            while (!CoreClosingControler) {
                List<Monster> mlist;
                if (View(out mlist)) {
                    foreach (var mon in mlist.Where(tem => tem.Type == 7 && tem.Name == name && tem.Flag >= 0)) {
                        TheMenPai = new MenPai(mon.Flag);
                        return;
                    }
                }
                Thread.Sleep(200);
            }
        }

        #endregion

        #region 自动寻路

        /// <summary>
        /// 走到当前地图的某个坐标
        /// </summary>
        /// <param name="txy"></param>
        public void WalkToXy(XY txy, string temMap = null) {
            //参数不合法直接返回
            if (!txy.Islegal())
                return;
            //状态记录
            temMap = temMap ?? TheGamer.MapName;
            if (string.IsNullOrEmpty(temMap))
                return;

            var temXy = new XY();
            DateTime temTime = DateTime.Now;//每一次成功移动超过了5就记录一下 并且记录下记录时间 用于卡机处理->>

            Controler.WalkControler = true;

            while (txy.HowFar(TheGamer.JsXY) > 2 && Controler.WalkControler) {
                Thread.Sleep(100);
                if (TheGamer.MapName != temMap)
                    break;//变化返回
                if (TheGamer.MapChangeCounter < 10)
                    continue;
                if (TheGamer.JsStaticCounter > 5 || (TheGamer.State == 2 && txy != _tarXy)) {
                    Walk(txy);
                    Thread.Sleep(1000);
                }
                if (TheGamer.JsXY.HowFar(temXy) > 15) {
                    temXy = TheGamer.JsXY;
                    temTime = DateTime.Now;
                    Thread.Sleep(100);
                    //Debug.WriteLine("记录移动新坐标……");
                }
                else if (TheGamer.JsStaticCounter > 30 ||
                    (TheGamer.MapChangeCounter > 30 && DateTime.Now.Subtract(temTime).TotalSeconds > 20)) {
                    Debug.WriteLine("卡机捕获……");
                    RandomWalk();
                    temTime = DateTime.Now;
                }
                if (TheGamer.Horse)
                    continue;
                if (TheGamer.State == 2 &&
                    txy.HowFar(TheGamer.JsXY) > 60f &&
                    TheMenPai != null &&
                    TheMenPai.SpeedSkill != null &&
                    DateTime.Now.Subtract(TheMenPai.SpeedSkill.LastReleaseTime).TotalSeconds > TheMenPai.SpeedSkill.CoolDown &&
                    TheGamer.MP > 500
                    ) {
                    Thread.Sleep(1000);
                    Skill_Common(TheMenPai.SpeedSkill.SkillID);
                    Thread.Sleep(1000);
                    TheMenPai.SpeedSkill.LastReleaseTime = DateTime.Now;
                    Walk(txy);
                    Thread.Sleep(1000);
                }
            }
        }

        /// <summary>
        /// 自动寻路
        /// </summary>
        /// <param name="tarMap"></param>
        /// <param name="horse"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public bool Walk(string tarMap, bool horse = true, float x = -1f, float y = -1f) {
            if (TheGamer.MapName == "地府" || TheGamer.MapName == "监狱" || string.IsNullOrEmpty(tarMap)) {
                return false;
            }
            Controler.WalkControler = true;
            var routs = new List<string>();

            string[] citys = { "大理", "洛阳", "苏州", "凤鸣镇", "楼兰" };
            string foreMap = null;
            var targetXy = new XY();
            int iCityIndex = -1;
            int iNowMapIndex = -1;
            string npcName = null;

            if (horse && !TheGamer.Horse)
                HorseOperate(true);

            while (!CoreClosingControler && Controler.WalkControler && TheGamer.MapName != tarMap) {
                Thread.Sleep(200);
                //路径解码没有完成
                if (routs.Count < 1) {
                    #region 路径解析
                    if (AutoRouting.GetRoute(TheGamer.MapName, tarMap, routs)) {
                        if (horse) {
                            string headCity = null;
                            string nextCity = null;
                            foreach (string temMap in routs) {
                                if (citys.Contains(temMap)) {
                                    if (string.IsNullOrEmpty(headCity))
                                        headCity = temMap;
                                    nextCity = temMap;
                                }
                            }
                            if (!string.IsNullOrEmpty(headCity) && headCity != nextCity) {
                                int ista = routs.IndexOf(headCity);
                                int isto = routs.IndexOf(nextCity);
                                routs.RemoveRange(ista + 1, isto - ista - 1);
                                iCityIndex = ista;
                            }
                        }
                    }
                    else {
                        return false;
                    }

                    #endregion
                }
                else if (!string.IsNullOrEmpty(TheGamer.MapName)) {
                    if (TheGamer.MapName != foreMap) {
                        #region 坐标分配
                        iNowMapIndex = routs.IndexOf(TheGamer.MapName);
                        if (iNowMapIndex < 0)
                            return false;//已经在不合法的路径中了
                        if (routs[iNowMapIndex] == tarMap)
                            return true;    //已经超过路径 到了地方
                        if (iCityIndex >= 0 && iCityIndex == iNowMapIndex) {
                            switch (routs[iNowMapIndex]) {
                                case "洛阳":
                                    targetXy.X = 235f;
                                    targetXy.Y = 322f;
                                    npcName = "吴德昌";
                                    break;
                                case "苏州":
                                    targetXy.X = 204;
                                    targetXy.Y = 256f;
                                    npcName = "李乘风";
                                    break;
                                case "大理":
                                    targetXy.X = 253f;
                                    targetXy.Y = 121f;
                                    npcName = "崔逢九";
                                    break;
                                case "楼兰":
                                    targetXy.X = 285f;
                                    targetXy.Y = 130f;
                                    npcName = "艾尼瓦尔";
                                    break;
                                case "凤鸣镇":
                                    targetXy.X = 154f;
                                    targetXy.Y = 115f;
                                    npcName = "罗泌";
                                    break;
                            }
                        }
                        else if (!AutoRouting.GetPoint(routs[iNowMapIndex], routs[iNowMapIndex + 1], ref targetXy)) {
                            Debug.WriteLine("无法加载传送点数据");
                            return false;//加载不出传送点
                        }
                        foreMap = routs[iNowMapIndex];
                        #endregion
                    }
                    else {
                        if (targetXy.HowFar(TheGamer.JsXY) > 2) {
                            WalkToXy(targetXy);
                        }
                        else if (TheGamer.JsStaticCounter > 10) {
                            if (iNowMapIndex == iCityIndex) {
                                var npc = new Monster();
                                if (GetNpc(npcName, ref npc)) {
                                    string diaContent = routs[iNowMapIndex + 1];
                                    if (diaContent == "凤鸣镇")
                                        diaContent = "KVKGZ_110620_128";
                                    if (routs[iNowMapIndex] == "凤鸣镇")
                                        diaContent = "XYXLY_110720_08";
                                    if (TalkNpc(npc.ID, diaContent)) {
                                        for (int i = 0; i < 80; i++) {
                                            if (TheGamer.State == -1)
                                                break;
                                            Thread.Sleep(100);
                                        }
                                    }
                                    Thread.Sleep(1000);
                                }
                            }
                            else if (TheGamer.JsStaticCounter > 200) {
                                RandomWalk();
                            }
                            else if (TheGamer.JsStaticCounter > 100) {
                                ConfirmBtnDeal();
                            }
                        }
                    }
                }
            }
            if (TheGamer.MapName != tarMap)
                return false;
            WalkToXy(x, y);
            if (TheGamer.JsXY.HowFar(x, y) > 2)
                return false;
            return true;

        }

        /// <summary>
        /// 走到当前地图的某个坐标
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        private void WalkToXy(float x, float y) {
            WalkToXy(new XY(x, y));
        }

        /// <summary>
        /// 地图进入确定
        /// </summary>
        /// <returns></returns>
        private bool ConfirmBtnDeal() {
            bool result = false;
            try {
                if (TheGamer.Dati) {
                    return false;
                }
                const string str = "确定";
                const string color = "ffff00-02ffff";

                int num;
                int num2;
                while (dm.DmRcWord(str, color, out num, out num2)) {
                    result = true;
                    dm.DmClick(num + 14, num2 + 7);
                    Thread.Sleep(500);
                    if (dm.DmRcWord(str, color, out num, out num2)) {
                        dm.DmClick(num + 14, num2 + 7);
                    }
                    Thread.Sleep(500);
                }
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch {

            }
            return result;
        }

        /// <summary>
        /// 随机移动
        /// </summary>
        public void RandomWalk() {
            do {
                var r = new Random();
                var iDirection = r.Next(360);//方向控制器
                var iDistances = r.Next(4, 8);//距离控制
                var x = TheGamer.JsXY.X + (float)Math.Cos(iDirection) * iDistances;
                var y = TheGamer.JsXY.Y + (float)Math.Sin(iDirection) * iDistances;
                Walk(x, y);
                Thread.Sleep(800);
            } while (TheGamer.JsStaticCounter > 0 && !CoreClosingControler && Controler.WalkControler);
        }
        #endregion

        #region 环境遍历

        /// <summary>
        /// 环境遍历
        /// </summary>
        /// <returns></returns>
        public bool View(out List<Monster> monList) {
            //DateTime nw = DateTime.Now;
            monList = new List<Monster>();
            var may = new Stack<int>();
            var addrs = new Stack<int>(100);
            addrs.Push(NativeMethods.Ri(dwProcessId, Data.JS, 100, 4));
            while (addrs.Count > 0 && addrs.Count < 400) {
                var tem = addrs.Pop();
                if (NativeMethods.Rb(dwProcessId, tem + 0x15) == 0) {
                    may.Push(tem);
                    addrs.Push(NativeMethods.Ri(dwProcessId, tem));
                    addrs.Push(NativeMethods.Ri(dwProcessId, tem + 8));
                }
            }
            if (addrs.Count < 400) {
                foreach (var start in may) {
                    var temMon = new Monster { ID = NativeMethods.Ri(dwProcessId, start + 0xC) };
                    if (temMon.ID < 0)
                        continue;
                    var treeObject1 = NativeMethods.Ri(dwProcessId, start + 0x10);
                    //距离计算
                    temMon.MonXy.X = NativeMethods.Rf(dwProcessId, treeObject1 + 0x48);
                    temMon.MonXy.Y = NativeMethods.Rf(dwProcessId, treeObject1 + 80);
                    temMon.HowFar = temMon.MonXy.HowFar(TheGamer.JsXY);

                    temMon.Type = NativeMethods.Ri(dwProcessId, treeObject1 + 0x2c, 0x18);
                    if (temMon.Type == 7) {

                        //要实现对包裹数据的自动识别就必须做到几个方面:
                        //1.对数据执行版本校正
                        //2.对包裹实现数据捡取结果监察
                        // 检测的方式：
                        // 发现地面包裹 --> 执行捡取 --> 捡取成功 --> id 消失
                        //  id  发现时间 捡取时间 消失时间
                        //  遍历 怀疑观察 重点考察 确定
                        //3.每次游戏更新之后就需要进行相应的数据更新校正
                        //1.使用共享数据来进行处理
                        //2.任务位置的影响

                        var bagid = NativeMethods.Ri(dwProcessId, treeObject1, 400);
                        if ((floorBagId.Value > 0 && bagid == floorBagId.Value) || (floorBagId.Value < 0 && Math.Abs(bagid - Data.ID_FLOORBAG) < 0x10000)) {
                            temMon.IsBag = true;
                            //用于临时缓存id
                            temMon.TreeObject2 = bagid;
                            monList.Add(temMon);
                            continue;
                        }

                        Console.WriteLine("trace->地面包裹编号:{0}", bagid.ToString("x"));
                    }
                    temMon.TreeObject2 = NativeMethods.Ri(dwProcessId, treeObject1 + Data.JS_OFF_2, 4);
                    temMon.Name = NativeMethods.Rs(dwProcessId, temMon.TreeObject2 + Data.JS_NAME);
                    temMon.Flag = NativeMethods.Ri(dwProcessId, temMon.TreeObject2 + 0x4c);
                    temMon.HP = NativeMethods.Rf(dwProcessId, temMon.TreeObject2 + 8);
                    temMon.Level = NativeMethods.Ri(dwProcessId, temMon.TreeObject2 + Data.JS_LEVEL);

                    if (string.IsNullOrEmpty(temMon.Name)) {
                        temMon.Name = NativeMethods.Rs(dwProcessId, treeObject1 + Data.OFF_VIEW_DRUG, 4, 0);
                    }
                    monList.Add(temMon);
                }
                return true;
            }
            return false;
        }

        /// <summary>
        /// 由NPC的名字取出离角色最近的那个NPC
        /// </summary>
        /// <param name="npcName">NPC名字</param>
        /// <param name="npc">返回NPC的信息</param>
        /// <returns>是否存在NPC</returns>
        public bool GetNpc(string npcName, ref Monster npc) {
            List<Monster> mlist;
            if (View(out mlist)) {
                var me = mlist.Where(tem => tem.Type == 3 && tem.Flag >= 0 && tem.Name == npcName).OrderBy(tem => tem.HowFar);
                foreach (var mon in me) {
                    npc = mon;
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region  背包数据
        /// <summary>
        /// 使用角色背包
        /// </summary>
        /// <param name="idlist"></param>
        private void UseBag(List<int> idlist, bool justOpen = false) {
            if (idlist.Count < 1)
                return;
            for (int i = 0; i < 5; i++) {
                if (dm.GetWindowState(3) == 1) {
                    dm.SetWindowState(12);
                    Thread.Sleep(2000);
                }
                else { break; }
            }
            const string str = "跑商包裹接口";
            const string color = "fdeb78-1fffff";
            dm.DmClick(50, 50, 0);
            if (NativeMethods.Ri(dwProcessId, Data.FLAG_BAG_JS, Data.FLAG_OFF_1, Data.FLAG_OFF_2, Data.FLAG_OFF_3) != 1) {
                dm.DmKeyPress("a");
                Thread.Sleep(2000);
            }
            int num;
            int num2;
            if (!dm.DmRcWord(str, color, out num, out num2)) {
                return;
            }
            int num3 = -1;
            foreach (int current in idlist) {
                int num4 = current / 30;
                if (num4 != num3) {
                    num3 = num4;
                    dm.DmClick(num - 88 + num3 * 44, num2 + 6, 2);
                    Thread.Sleep(400);
                }
                if (!justOpen)
                    dm.DmClick(num - 82 + current % 5 * 34, num2 + 35 + 34 * (current % 30 / 5), 2, false);
            }
        }

        /// <summary>
        /// 判断背包是否存在空格子
        /// </summary>
        /// <param name="bagId">包裹序号0 道具 1材料 2任务</param>
        /// <returns></returns>
        private bool HasEmptyBag(int bagId) {
            var gzCount = (int)NativeMethods.Rb(dwProcessId, Data.PET, Data.BAG_OFF_GZCOUNT + bagId);
            var i = bagId * 30;
            var maxGzIndex = i + gzCount;
            var bagObject = NativeMethods.Ri(dwProcessId, Data.PET, Data.BAG_OFF);
            while (i < maxGzIndex) {
                if (NativeMethods.Ri(dwProcessId, bagObject + i * 4, Data.BAG_ID) != i) {
                    return true;
                }
                i++;
            }
            return false;
        }
        /// <summary>
        /// 背包遍历
        /// </summary>
        /// <param name="baglist"></param>
        /// <param name="start"></param>
        /// <param name="stop"></param>
        public void ViewMyBag(out List<GamerBag> baglist, int start = 0, int stop = 80) {
            baglist = new List<GamerBag>();
            int bagObject = NativeMethods.Ri(dwProcessId, Data.PET, Data.BAG_OFF);
            for (int i = start; i < stop; i++) {
                var off = bagObject + i * 4;
                if (NativeMethods.Ri(dwProcessId, off, Data.BAG_ID) == i) {
                    var temBag = new GamerBag {
                        ID = i,
                        Num1 = NativeMethods.Ri(dwProcessId, off, Data.BAG_PRICE_OFF, Data.BAG_PRICE_1),
                        Num2 = NativeMethods.Ri(dwProcessId, off, Data.BAG_PRICE_OFF, Data.BAG_PRICE_2),
                        Sort = NativeMethods.Rs(dwProcessId, off, Data.BAG_STRING_OFF, Data.BAG_SORT, 0),
                        Name = NativeMethods.Rs(dwProcessId, off, Data.BAG_STRING_OFF, Data.BAG_NAME_1, 0)
                    };
                    if (string.IsNullOrEmpty(temBag.Name)) {
                        temBag.Name = NativeMethods.Rs(dwProcessId, off, Data.BAG_STRING_OFF, Data.BAG_NAME_2, 0);
                        if (string.IsNullOrEmpty(temBag.Name)) {
                            temBag.Name = NativeMethods.Rs(dwProcessId, off, Data.BAG_STRING_OFF, Data.BAG_NAME_3, 0);
                        }
                    }
                    baglist.Add(temBag);
                }
            }
        }
        #endregion

        #region 头像数据

        /// <summary>
        /// 头像图片缓存
        /// </summary>
        private System.Drawing.Image image;

        /// <summary>
        /// 头像图片
        /// </summary>
        /// <returns></returns>
        public System.Drawing.Image GetHeader() {
            if (image == null && !string.IsNullOrEmpty(PermaName)) {
                const string headerPath = "./user/头像/";
                if (!Directory.Exists(headerPath))
                    Directory.CreateDirectory(headerPath);
                string headerName = headerPath + PermaName + ".png";
                if (File.Exists("./user/头像/" + PermaName + ".png") || dm.CapturePng(4, 15, 60, 70, headerName)) {
                    var fs = File.OpenRead(headerName);
                    image = System.Drawing.Image.FromStream(fs);
                    fs.Close();
                }
            }
            return image;
        }

        #endregion

        #region 采集项目

        /// <summary>
        /// 采集线程函数
        /// </summary>
        private void CaiJiMainThread() {
            #region 配置检查并且加载坐标系统
            var luPath = new List<XY>();
            int luId = 0;
            if (!CaiJiConfigCheck(ref luPath))
                return;
            #endregion


            #region 常用数据初始化
            Controler.CJControler = true;
            WorkStateShow(GameState.采集);
            var kw = new Monster();
            Skill ys = TheMenPai.MyMenPai == MenPaiSet.天山 ? new Skill(false, 0x1f1, 300) : new Skill(false, 0xf8, 35);

            ys.LastReleaseTime = DateTime.Now.AddMinutes(-10);

            XY lsXy = TheGamer.JsXY;
            DateTime lsCheckTime = DateTime.Now;
            #endregion

            while (!CoreClosingControler && Controler.CJControler) {
                Thread.Sleep(10);
                if (CaiJiStateDealing()) {
                    if (CaiJiSearching(ref kw)) {
                        WalkToXy(kw.MonXy);
                        if (TheGamer.Horse) {
                            HorseOperate(false);
                            for (int i = 0; i < 50; i++) {
                                Thread.Sleep(100);
                                if (!TheGamer.Horse)
                                    break;
                            }
                        }
                        if (Conf.CaiJiYS.Value && (DateTime.Now - ys.LastReleaseTime).TotalSeconds > ys.CoolDown) {
                            Thread.Sleep(500);
                            Skill_Common(ys.SkillID);
                            Thread.Sleep(1000);
                            ys.LastReleaseTime = DateTime.Now;
                        }
                        CaiJiMining(ref kw);
                    }
                    else {
                        CaiJiMoving(luPath, ref luId, ref lsXy, ref lsCheckTime);
                    }
                }
            }
            WorkStateShow(GameState.空闲);
        }

        /// <summary>
        /// 采集坐标状态
        /// </summary>
        /// <param name="luPath"></param>
        /// <param name="luId"></param>
        /// <param name="lsXy"></param>
        /// <param name="lsCheckTime"></param>
        private void CaiJiMoving(List<XY> luPath, ref int luId, ref XY lsXy, ref DateTime lsCheckTime) {
            if (TheGamer.MapChangeCounter < 30)
                return;
            if (luPath[luId].HowFar(TheGamer.JsXY) < 4) {
                luId++;
                if (luId >= luPath.Count)
                    luId = 0;
                if (!Conf.CaiJiYS.Value || TheMenPai.MyMenPai != MenPaiSet.天山) {
                    HorseOperate(true);
                }
                Walk(luPath[luId]);
                Thread.Sleep(100);
            }
            else if (TheGamer.JsStaticCounter > 5) {
                if (!Conf.CaiJiYS.Value || TheMenPai.MyMenPai != MenPaiSet.天山) {
                    HorseOperate(true);
                }
                Walk(luPath[luId]);
                Thread.Sleep(100);
                if (TheGamer.JsStaticCounter > 50)
                    RandomWalk();
            }
            else if (lsXy.HowFar(TheGamer.JsXY) > 5) {
                lsCheckTime = DateTime.Now;
                lsXy = TheGamer.JsXY;
            }
            else if ((DateTime.Now - lsCheckTime).TotalSeconds > 50) {
                RandomWalk();
                Thread.Sleep(100);
            }
        }

        /// <summary>
        /// 采集矿物
        /// </summary>
        /// <param name="kw"></param>
        private void CaiJiMining(ref Monster kw) {
            Catch(kw.ID, false);
            Thread.Sleep(1000);
            while (!CoreClosingControler && Controler.CJControler && TheGamer.JsStaticCounter < 10) {
                Thread.Sleep(20);
                //Console.WriteLine("1:{0}", NativeMethods.Ri(dwProcessId, Data.FLAG_BAG_FLOOR, Data.FLAG_OFF_1, Data.FLAG_OFF_2, Data.FLAG_OFF_3));
                if (NativeMethods.Ri(dwProcessId, Data.FLAG_BAG_FLOOR, Data.FLAG_OFF_1, Data.FLAG_OFF_2, Data.FLAG_OFF_3) == 1) {
                    for (int i = 0; i < 50; i++) {
                        //Console.WriteLine("2:{0}", NativeMethods.Ri(dwProcessId, Data.FLAG_BAG_FLOOR, Data.FLAG_OFF_1, Data.FLAG_OFF_2, Data.FLAG_OFF_3));
                        if (i % 10 == 0) {
                            Catch();
                            Thread.Sleep(200);
                        }
                        Thread.Sleep(100);
                        if (NativeMethods.Ri(dwProcessId, Data.FLAG_BAG_FLOOR, Data.FLAG_OFF_1, Data.FLAG_OFF_2, Data.FLAG_OFF_3) == 0) { break; }
                    }
                    break;
                }
            }
            if (CoreClosingControler && !Controler.CJControler || NativeMethods.Ri(dwProcessId, Data.JS, Data.JS_OFF_1, Data.JS_OFF_2, Data.JS_OFF_3, Data.JS_ENERGY) < Conf.CaiJiMinEnergy.Value)
                return;
            if (CaiJiSearching(ref kw)) {
                WalkToXy(kw.MonXy);
                CaiJiMining(ref kw);
            }
        }

        /// <summary>
        /// 坐骑操作
        /// </summary>
        /// <param name="getOnHorse"></param>
        private void HorseOperate(bool getOnHorse) {
            if ((getOnHorse && TheGamer.Horse) || (!getOnHorse && !TheGamer.Horse))
                return;
            if (getOnHorse) {
                int num = 3;
                while (!TheGamer.Horse && num > 0 && !CoreClosingControler) {
                    if (TheGamer.JsStaticCounter > 5) {
                        Skill_Common(0x15);
                        num--;
                        Thread.Sleep(500);
                    }
                    Thread.Sleep(100);
                }
            }
            else {
                Skill_Common(0x15);
                for (int i = 0; i < 100; i++) {
                    if (NativeMethods.Ri(dwProcessId, Data.JS, Data.JS_OFF_1, Data.JS_OFF_2, Data.JS_OFF_3, Data.JS_HORSE) == 1)
                        break;
                    Thread.Sleep(50);
                }
                Thread.Sleep(50);
            }
        }

        /// <summary>
        /// 矿物搜索
        /// </summary>
        /// <param name="kw"></param>
        /// <returns></returns>
        private bool CaiJiSearching(ref Monster kw) {
            List<Monster> mlist;
            if (View(out mlist)) {
                var ie = mlist.Where(mon => !string.IsNullOrEmpty(mon.Name) && Conf.CaiJiMinerals.Value.Contains(mon.Name) &&
                          mlist.Count(jsMon => jsMon.Type == 11 && jsMon.MonXy.HowFar(mon.MonXy) < 4) == 0).OrderBy(tem => tem.HowFar);
                foreach (var tem in ie) {
                    if (tem.ID == kw.ID) {
                        if (tem.MonXy.HowFar(TheGamer.JsXY) < 2)
                            return false;
                        Walk(tem.MonXy);
                        Thread.Sleep(500);
                    }
                    kw = tem;
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 采集状态检查
        /// </summary>
        /// <returns>是否满足继续采集的条件</returns>
        private bool CaiJiStateDealing() {
            //精力值非法检查
            if (TheGamer.MapChangeCounter < 30 || TheGamer.Energy < 0)
                return false;
            //进入休整条件：1.背包没有空格了  2.精力已经不足再次采集了 3.副本条件下
            if (!HasEmptyBag(1) || TheGamer.Energy < Conf.CaiJiMinEnergy.Value) {
                if (!HasEmptyBag(1))
                    SendMessageToUi("人物背包已满,进入休息.");
                //如果是和尚副本线程调用在这个时候返回主线程部分
                if (Controler.HFControler && Conf.HFCJ.Value) {
                    Controler.CJControler = false;
                    return false;
                }
                int energyMax = TheGamer.EnergyMax;
                bool isFirstGotoLuoYang = !Conf.CaiJiYuanDiRest.Value;
                WorkStateShow(GameState.休息);
                while (!CoreClosingControler && Controler.CJControler && energyMax > 0) {
                    Thread.Sleep(200);
                    if (isFirstGotoLuoYang) {
                        if (!string.IsNullOrEmpty(TheGamer.MapName) && TheGamer.MapName != "洛阳") {
                            if (Walk("洛阳") && !CoreClosingControler && Controler.CJControler) {
                                for (int i = 0; i < 100; i++) {
                                    Thread.Sleep(100);
                                    if (CoreClosingControler || !Controler.CJControler) {
                                        break;
                                    }
                                }
                                //下马打坐休息
                                if (!CoreClosingControler && Controler.CJControler) {
                                    if (Controler.ZZControler) {
                                        Controler.CJControler = false;
                                        return false;
                                    }
                                    HorseOperate(false);
                                    Thread.Sleep(2000);
                                    Skill_JS(0x23);
                                    isFirstGotoLuoYang = false;
                                    //最小化
                                    //窗口最小化
                                    if (dm.GetWindowState(3) == 0 && !TheGamer.Dati) {
                                        dm.SetWindowState(2);
                                        Thread.Sleep(200);
                                    }
                                }
                            }
                        }
                    }
                    else if (TheGamer.Energy > 250 && HasEmptyBag(1)) {
                        //恢复到窗口最大化
                        if (dm.GetWindowState(3) == 1) {
                            dm.SetWindowState(12);
                            Thread.Sleep(200);
                        }
                        break;
                    }
                }
                WorkStateShow(GameState.采集);
                return false;
            }
            if (TheGamer.HPMax * 0.3 > TheGamer.HP) {
                if (TheGamer.MapName == "洛阳") {
                    LuoYangHealth();
                }
                else {
                    Walk("洛阳");
                }
            }
            else if (TheGamer.MapName != Conf.CaiJiMap.Value) {
                Walk(Conf.CaiJiMap.Value);
                return false;
            }
            else if (TheGamer.MapChangeCounter < 100) {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 采集配置检查
        /// 路径坐标加载
        /// </summary>
        /// <param name="lu">路径坐标</param>
        /// <returns></returns>
        private bool CaiJiConfigCheck(ref List<XY> lu) {
            if (string.IsNullOrEmpty(Conf.CaiJiMap.Value) || string.IsNullOrEmpty(Conf.CaiJiMinerals.Value)) {
                MsgListener.MsgBoxMsgShow("采集配置必备配置项目未完善,请先完成配置！", "采集配置");
                return false;
            }
            string zuoBiaoFielName = "./SYSTEM/" + Conf.CaiJiMap.Value.Trim() + ".txt";
            if (!ZuoBiao(zuoBiaoFielName, ref lu)) {
                MsgListener.MsgBoxMsgShow("采集坐标文件解析失败了！", "采集配置");
                return false;
            }
            if (Conf.CaiJiMinEnergy.Value == 0)//保留精力默认值
                Conf.CaiJiMinEnergy.Value = 12;
            int max = lu.Count - 1;
            //随机化坐标序列
            var r = new Random();
            for (int i = 0; i < lu.Count; i++) {
                XY tem = lu[i];
                int index = r.Next(i, max);
                lu[i] = lu[index];
                lu[index] = tem;
            }
            return true;
        }

        /// <summary>
        /// 从文件加载坐标系统
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="luPath"></param>
        /// <returns></returns>
        private bool ZuoBiao(string fileName, ref List<XY> luPath) {
            if (!File.Exists(fileName)) {
                MsgListener.MsgBoxMsgShow("所需地图文件缺失！", "坐标解析");
                return false;
            }

            var fileContext = new StringBuilder(File.ReadAllText(fileName));
            fileContext = fileContext.Replace("(", "");
            fileContext = fileContext.Replace(")", "");
            //按行分割
            string[] lineArray = fileContext.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string luStr in lineArray) {
                string[] luArray = luStr.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (luArray.Length == 2) {
                    XY temXy;
                    if (float.TryParse(luArray[0], out temXy.X) && float.TryParse(luArray[1], out temXy.Y)) {
                        luPath.Add(temXy);
                    }
                }
            }
            if (luPath.Count == 0)
                return false;
            return true;
        }

        #endregion

        #region 炼金任务
        /// <summary>
        /// 炼金任务主线程
        /// </summary>
        private void LianJinThread() {
            WorkStateShow(GameState.炼金);
            Controler.LJControler = true;

            var theLianJinData = new LianJinData {
                NowMessionState = LianJinMessionState.未知任务态
            };

            while (!CoreClosingControler && Controler.LJControler) {
                Thread.Sleep(200);
                if (LianJinMapCheck()) {
                    switch (theLianJinData.NowMessionState) {
                        case LianJinMessionState.未知任务态:
                            LianJinMessionDealing(ref theLianJinData);
                            break;
                        case LianJinMessionState.搬运未完成:
                            LianJinBanyun(ref  theLianJinData);
                            break;
                        case LianJinMessionState.采集未完成:
                            LianJinCaiJi(ref theLianJinData);
                            break;
                    }
                }
            }
            WorkStateShow(GameState.空闲);
        }


        /// <summary>
        /// 任务字符串垃圾字符清理
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string StringToLegal(string str) {
            var sb = new StringBuilder(str.Length);
            foreach (char t in str) {
                if (t > 40) {
                    sb.Append(t);
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 炼金之收集任务
        /// </summary>
        /// <param name="theLianJinData"></param>
        public void LianJinCaiJi(ref LianJinData theLianJinData) {
            string str = GetTaskMsg();
            dm.DmKeyPress("F2");
            string temStr = str;
            for (int i = 0; i < 20; i++) {
                Thread.Sleep(200);
                temStr = GetTaskMsg();
                if (temStr.StartsWith(LianJinData.LianJinStrStartFlag) && str != temStr)
                    break;
            }
            if (temStr == LianJinData.LianJinCaiJiWanCheng) {
                theLianJinData.NowMessionState = LianJinMessionState.未知任务态;
            }
            else if (temStr.StartsWith(LianJinData.LianJinStrStartFlag)) {
                str = StringToLegal(temStr).Replace("}", "");
                string[] strArr = str.Split(new[] { "*" }, StringSplitOptions.RemoveEmptyEntries);
                if (strArr.Length == 3) {
                    int x, y;
                    if (int.TryParse(strArr[1].Trim(), out x) &&
                        int.TryParse(strArr[2].Trim(), out y) &&
                        x > 10 && y > 10) {
                        //去挖
                        #region 去坐标标示位置挖矿
                        while (!CoreClosingControler && Controler.LJControler) {
                            if (TheGamer.JsXY.HowFar(x, y) > 2) {
                                WalkToXy(x, y);
                                Thread.Sleep(500);
                            }
                            else if (TheGamer.JsStaticCounter > 5) {
                                if (TheGamer.JsStaticCounter > 200)
                                    break;
                                dm.DmKeyPress("f1");
                                Thread.Sleep(200);
                            }
                            else if (TheGamer.State != 2 && TheGamer.JsStaticCounter == 0) {
                                //等待收集矿物//
                                break;
                            }
                            Thread.Sleep(200);
                        }
                        #endregion

                        #region 等待检查是否需要自己捡东西

                        bool reCheck = false;
                        while (!CoreClosingControler && Controler.LJControler) {
                            if (TheGamer.JsStaticCounter > 10) {
                                List<Monster> mlist;
                                if (View(out mlist)) {
                                    Monster[] floorBags = (from mon in mlist where mon.IsBag orderby mon.HowFar select mon).ToArray();
                                    if (floorBags.Length > 0) {
                                        if (!Controler.JWControler) {
                                            foreach (Monster monster in floorBags) {
                                                Catch(monster.ID);
                                                Thread.Sleep(2000);
                                            }
                                        }
                                    }
                                    else if (reCheck) {
                                        break;
                                    }
                                    else {
                                        reCheck = true;
                                    }
                                }
                            }
                            Thread.Sleep(200);
                        }
                        return;
                        #endregion
                    }
                }
            }
            if (theLianJinData.iCaiJiFailCounter++ > 30)
                Controler.LJControler = false;
        }

        /// <summary>
        /// 炼金搬运任务
        /// </summary>
        /// <param name="theLianJinData"></param>
        private void LianJinBanyun(ref LianJinData theLianJinData) {
            //Debug.WriteLine("进入搬运处理");
            WalkToXy(theLianJinData.BanyunNPCPositon);
            if (TheGamer.JsXY.HowFar(theLianJinData.BanyunNPCPositon) < 2) {
                //MsgListener.CommonMsgShow(PermaName, "搬运NPC查询……");
                List<Monster> mList;
                if (View(out mList)) {
                    string temDiaStr = theLianJinData.LianJinBanyunStr;
                    List<Monster> npcArr = (from mon in mList
                                            where mon.Type == 3 && mon.Flag >= 0 && mon.HowFar < 3 && temDiaStr.Contains(mon.Name)
                                            select mon).ToList();
                    if (npcArr.Count == 1) {
                        //Debug.WriteLine("对话开始搬运……");
                        Monster temNpc = npcArr[0];//对话搬运
                        WalkToXy(temNpc.MonXy);
                        Thread.Sleep(200);
                        if (TalkNpc(temNpc.ID, LianJinData.LianJinKaiShiBanYun)) {
                            Thread.Sleep(2000);
                            theLianJinData.NowMessionState = LianJinMessionState.未知任务态;
                            return;
                        }
                    }
                }
            }
            if (theLianJinData.iBanyunFailCounter++ > 30)
                Controler.LJControler = false;
        }

        /// <summary>
        /// NPC对话信息检查
        /// </summary>
        /// <param name="diaStr"></param>
        /// <returns></returns>
        public bool NpcDiaCheck(string diaStr) {
            var temStr = diaStr;
            return NpcDiaCheck(ref temStr);
        }

        /// <summary>
        /// 检查并且返回完整的对话字符串
        /// </summary>
        /// <param name="diaStr"></param>
        /// <returns></returns>
        public bool NpcDiaCheck(ref string diaStr) {
            if (string.IsNullOrEmpty(diaStr))
                return false;
            int btnCount = NativeMethods.Rb(dwProcessId, Data.CALL_NPCDIA, 0x34, 4);
            for (int i = 0; i < btnCount; i++) {
                string temStr = NativeMethods.Rs(dwProcessId, Data.CALL_NPCDIA, 0x34, (8 + (i * 0x118)) + 0xe);
                //对话信息
                if (temStr.Contains(diaStr)) {
                    diaStr = temStr;
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 炼金接任务
        /// </summary>
        /// <param name="theLianJinData"></param>
        private void LianJinMessionDealing(ref LianJinData theLianJinData) {
            if (TheGamer.Dati)
                return;
            if (TheGamer.JsXY.HowFar(LianJinData.MessionNpcPosition) > 2) {
                //Debug.WriteLine("走到戴三金的位置……");
                WalkToXy(LianJinData.MessionNpcPosition);
                Thread.Sleep(100);
                theLianJinData.iAcceptFailCounter = 0;
            }
            else if (theLianJinData.MessionNPC == null || theLianJinData.MessionNPC.ID < 1) {
                //Debug.WriteLine("NPC捕捉……");
                GetNpc("戴三金", ref theLianJinData.MessionNPC);
            }
            else if (TheGamer.JsStaticCounter > 20) {
                if (TheGamer.Horse) {
                    //Debug.WriteLine("下马……");
                    HorseOperate(false);
                }
                else if (TalkNpc(theLianJinData.MessionNPC.ID, LianJinData.LianJinRenWu)) {
                    Thread.Sleep(1000);
                    //MsgListener.CommonMsgShow(PermaName, "接任务");
                    var temState = MessionState.未知;
                    if (AcceptOrFinish(ref temState)) {
                        switch (temState) {
                            case MessionState.未知:
                                MsgListener.CommonMsgShow(PermaName, "存在未完成的任务");
                                if (TalkNpc(theLianJinData.MessionNPC.ID, LianJinData.LianJinHuoQuBianShen)) {
                                    #region 未完成的搬运任务
                                    theLianJinData.NowMessionState = LianJinMessionState.采集未完成;
                                    theLianJinData.iCaiJiFailCounter = 0;
                                    #endregion
                                    return;
                                }
                                break;
                            case MessionState.需要接受:
                                if (NpcDiaCheck(LianJinData.LianJinCannotGetMoreMession)) {
                                    Controler.LJControler = false;
                                    MsgListener.CommonMsgShow(PermaName, "没有活跃了");
                                    return;
                                }
                                string temDiaStr = LianJinData.MessionNpcName;
                                if (NpcDiaCheck(ref temDiaStr)) {
                                    //MsgListener.CommonMsgShow(PermaName, temDiaStr);
                                    //MsgListener.MsgBoxMsgShow("把运行日志中出现的的以#{BHRWSC_开头的语句复制给漠然！", "反馈提示");
                                    #region 接受的是搬运任务
                                    //Debug.WriteLine("接受了一个搬运任务");
                                    temDiaStr = StringToLegal(temDiaStr);
                                    int index = temDiaStr.IndexOf("）*{BHRWSC_110331_53}*戴", StringComparison.Ordinal);
                                    if (index > 0) {
                                        theLianJinData.LianJinBanyunStr = temDiaStr;
                                        temDiaStr = temDiaStr.Remove(index);
                                        string[] temStrArr = temDiaStr.Split(new[] { "（" }, StringSplitOptions.RemoveEmptyEntries);
                                        if (temStrArr.Length == 2) {
                                            temDiaStr = temStrArr[1];
                                            temStrArr = temDiaStr.Split(new[] { "，" }, StringSplitOptions.RemoveEmptyEntries);
                                            if (temStrArr.Length == 2) {
                                                int x, y;
                                                if (int.TryParse(temStrArr[0], out x) && int.TryParse(temStrArr[1], out y)) {
                                                    theLianJinData.BanyunNPCPositon = new XY(x, y);
                                                    theLianJinData.NowMessionState = LianJinMessionState.搬运未完成;
                                                    theLianJinData.iBanyunFailCounter = 0;
                                                    //Debug.WriteLine("搬运任务信息采集成功");
                                                    return;
                                                }
                                            }
                                        }
                                    }
                                    #endregion
                                }
                                else {
                                    #region 接受的是采集任务
                                    //MsgListener.CommonMsgShow(PermaName, "接受了一个采集任务");
                                    theLianJinData.NowMessionState = LianJinMessionState.采集未完成;
                                    theLianJinData.iCaiJiFailCounter = 0;
                                    #endregion
                                    return;
                                }
                                break;
                        }
                    }
                    else {
                        Thread.Sleep(1000);
                        //MsgListener.CommonMsgShow(PermaName, "对话失败了");
                    }
                }
                if (theLianJinData.iAcceptFailCounter++ > 20) {
                    Controler.LJControler = false;
                }
            }
        }

        /// <summary>
        /// 接收或交还任务
        /// </summary>
        /// <param name="temState"></param>
        /// <returns></returns>
        private bool AcceptOrFinish(ref MessionState temState) {
            if (NativeMethods.Ri(dwProcessId, Data.FLAG_NPC, Data.FLAG_OFF_1, Data.FLAG_OFF_2, Data.FLAG_OFF_3) != 1)
                return false;
            const string grayColor = "bbbbbb-02ffff";
            const string activeColor = "fdeb78-02ffff";
            const string mutexColor = "bbbbbb-02ffff|fdeb78-02ffff";
            const string strAccept = "任务接受";
            const string strFinish = "任务完成";
            const string strContinue = "任务继续";
            int bx, by;
            if (!dm.DmRcWord("任务截取框", mutexColor, out bx, out by))
                return false;
            int temX, temY;
            //System.Drawing.Rectangle retangle = new System.Drawing.Rectangle(bx, by, 90, 27);
            if (!dm.DmRcWord(strAccept, grayColor, out temX, out temY, bx, by, bx + 90, by + 27)) {
                if (!dm.DmRcWord(strContinue, grayColor, out temX, out temY, bx, by, bx + 90, by + 27)) {
                    return false;
                }
                //没有找到接受按钮 找到是灰色不可用 的继续按钮
                int num5 = temX;
                int num6 = temY;
                temState = MessionState.需要接受;
                dm.DmClick(num5 - 28, num6 + 7);
                for (int i = 0; i < 10; i++) {
                    Thread.Sleep(1000);
                    if (dm.DmRcWord(strAccept, grayColor, out temX, out temY, num5 - 42, num6, num5, num6 + 20)) {
                        return true;
                    }
                    if (NativeMethods.Ri(dwProcessId, Data.FLAG_NPC, Data.FLAG_OFF_1, Data.FLAG_OFF_2, Data.FLAG_OFF_3) == 1) {
                        dm.DmClick(num5 - 28, num6 + 7);
                    }
                }
                return false;
            }
            if (dm.DmRcWord(strContinue, grayColor, out temX, out temY, bx, @by, bx + 90, @by + 27)) {
                temState = MessionState.未知;
                return true;
            }

            if (dm.DmRcWord(strContinue, activeColor, out temX, out temY, bx, @by, bx + 90, @by + 27)) {
                temState = MessionState.继续完成;
                int num5 = temX;
                int num6 = temY;
                dm.DmClick(num5 + 14, num6 + 7, 2);
                for (int j = 0; j < 10; j++) {
                    Thread.Sleep(1000);
                    if (dm.DmRcWord(strFinish, activeColor, out temX, out temY, num5, num6, num5 + 42, num6 + 20)) {
                        break;
                    }
                    if (NativeMethods.Ri(dwProcessId, Data.FLAG_NPC, Data.FLAG_OFF_1, Data.FLAG_OFF_2, Data.FLAG_OFF_3) == 1) {
                        dm.DmClick(num5 + 14, num6 + 7, 2);
                    }
                }
                if (temX == -1 || temY == -1) {
                    return false;
                }
            }
            if (dm.DmRcWord(strFinish, activeColor, out temX, out temY, bx, @by, bx + 90, @by + 27)) {
                temState = MessionState.完成;
                int num5 = temX;
                int num6 = temY;
                dm.DmClick(num5 + 14, num6 + 7);
                for (int k = 0; k < 5; k++) {
                    Thread.Sleep(1000);
                    if (dm.DmRcWord(strFinish, grayColor, out temX, out temY, num5, num6, num5 + 42, num6 + 20)) {
                        return true;
                    }
                    if (NativeMethods.Ri(dwProcessId, Data.FLAG_NPC, Data.FLAG_OFF_1, Data.FLAG_OFF_2, Data.FLAG_OFF_3) == 0) {
                        return true;
                    }
                    dm.DmClick(num5 + 14, num6 + 7);
                }
            }
            return false;
        }

        /// <summary>
        /// 炼金地图检查
        /// </summary>
        /// <returns></returns>
        private bool LianJinMapCheck() {
            if (TheGamer.MapName == Conf.msMyBanghuiMap.Value)
                return true;
            var npc = new Monster();
            if (Walk("洛阳", true, 236f, 236f) && GetNpc("范纯仁", ref npc) && TalkNpc(npc.ID, "进入本帮城市")) {
                for (int i = 0; i < 100; i++) {
                    Thread.Sleep(100);
                    if (TheGamer.MapName != "洛阳") {
                        Thread.Sleep(3000);
                        var tMap = TheGamer.MapName;
                        if (tMap == Conf.msMyBanghuiMap.Value) {
                            break;
                        }

                        while (!CoreClosingControler) {
                            if (!Controler.LJControler) {
                                return false;
                            }
                            if (TheGamer.MapChangeCounter > 40)
                                break;
                        }

                        bool change = false;
                        for (int j = 0; j < 10; j++) {
                            Thread.Sleep(1000);
                            if (TheGamer.MapName != tMap) {
                                change = true;
                                break;
                            }
                        }

                        if (!change) {
                            Conf.msMyBanghuiMap.Value = tMap;
                            SendMessageToUi("[帮会地图]:{0}", Conf.msMyBanghuiMap.Value);
                        }
                    }
                }
            }
            Thread.Sleep(500);
            return false;
        }


        #endregion

        #region 峨眉加血

        /// <summary>
        /// 峨眉加血
        /// </summary>
        public void EmHealthThread() {
            MsgListener.CommonMsgShow(PermaName, "开启峨眉加血功能！");
            Controler.EMControler = true;
            var temTeam = new List<TeamMember>();
            while (!CoreClosingControler && Controler.EMControler) {
                Thread.Sleep(100);
                if (TheGamer.Horse || TheGamer.MapChangeCounter < 30 || TheGamer.State == 2 || TheGamer.MP < 1200)
                    continue;
                TeamView(ref temTeam);

                var linq = temTeam
                    .Where(member => member.HPPercent > 0 && member.HPPercent < Conf.EMHealthPercent.Value / 100.0 && member.NwXY.HowFar(TheGamer.JsXY) < 13)
                    .OrderBy(member => member.HPPercent);

                foreach (var temMember in linq) {
                    if (Conf.EMCXYQ.Value)//冲虚养气
                    {

                        if (GetTimeSpanSeconds(EmHealthSkills.CXYQ.LastReleaseTime) > EmHealthSkills.CXYQ.CoolDown) {
                            Skill_Common(EmHealthSkills.CXYQ.SkillID, temMember.ID);
                            EmHealthSkills.CXYQ.LastReleaseTime = DateTime.Now;
                            Thread.Sleep(1000);
                        }
                    }
                    else if (Conf.EMFGPZ.Value) //佛光普照
                    {
                        if (GetTimeSpanSeconds(EmHealthSkills.FGPZ.LastReleaseTime) > EmHealthSkills.FGPZ.CoolDown) {
                            Skill_Common(EmHealthSkills.FGPZ.SkillID, temMember.ID);
                            EmHealthSkills.FGPZ.LastReleaseTime = DateTime.Now;
                            Thread.Sleep(1000);
                        }
                    }
                    else {
                        //清心菩提
                        if (GetTimeSpanSeconds(EmHealthSkills.QXPT.LastReleaseTime) > EmHealthSkills.QXPT.CoolDown) {
                            Skill_Common(EmHealthSkills.QXPT.SkillID, temMember.ID);
                            EmHealthSkills.QXPT.LastReleaseTime = DateTime.Now;
                            Thread.Sleep(1000);
                        }
                    }
                    //春花秋月
                    if (Conf.EMCHQY.Value) {
                        if (GetTimeSpanSeconds(EmHealthSkills.CHQY.LastReleaseTime) > EmHealthSkills.CHQY.CoolDown) {
                            Skill_Common(EmHealthSkills.CHQY.SkillID, temMember.ID);
                            EmHealthSkills.CHQY.LastReleaseTime = DateTime.Now;
                            Thread.Sleep(1000);
                        }
                    }
                    //金针渡劫
                    if (Conf.EMJZDJ.Value) {
                        if (GetTimeSpanSeconds(EmHealthSkills.JZDJ.LastReleaseTime) > EmHealthSkills.JZDJ.CoolDown) {
                            Skill_Common(EmHealthSkills.JZDJ.SkillID, temMember.ID);
                            EmHealthSkills.JZDJ.LastReleaseTime = DateTime.Now;
                            Thread.Sleep(1000);
                        }
                    }
                    break;
                }

            }
            MsgListener.CommonMsgShow(PermaName, "退出峨眉加血功能!");
        }

        /// <summary>
        /// 获取时间分割
        /// </summary>
        /// <param name="temTime"></param>
        /// <returns></returns>
        private int GetTimeSpanSeconds(DateTime temTime) {
            return (int)(DateTime.Now - temTime).TotalSeconds;
        }


        /// <summary>
        /// 队伍信息遍历
        /// </summary>
        /// <param name="temTeam"></param>
        private void TeamView(ref List<TeamMember> temTeam) {
            temTeam.Clear();
            int memberCount = NativeMethods.Ri(dwProcessId, Data.MAP, Data.MAP_OFF_1 + 60) + 1;
            if (memberCount > 1) {
                for (int i = 0; i < memberCount; i++) {
                    var item = new TeamMember {
                        Index = i,
                        ID = NativeMethods.Ri(dwProcessId, Data.TEAM, 0xc8, i * 4, 4),
                        Name = NativeMethods.Rs(dwProcessId, Data.TEAM, 0xc8, i * 4, 0x14)
                    };
                    if (item.Name == PermaName) {
                        item.HP = TheGamer.HP;
                        item.HPMax = TheGamer.HPMax;
                        item.NwXY.X = TheGamer.JsXY.X;
                        item.NwXY.Y = TheGamer.JsXY.Y;
                    }
                    else {
                        item.HP = NativeMethods.Ri(dwProcessId, Data.TEAM, 0xc8, i * 4, 0x4c);
                        item.HPMax = NativeMethods.Ri(dwProcessId, Data.TEAM, 0xc8, i * 4, 0x50);
                        item.NwXY.X = NativeMethods.Rf(dwProcessId, Data.TEAM, 0xc8, i * 4, 0x44);
                        item.NwXY.Y = NativeMethods.Rf(dwProcessId, Data.TEAM, 0xc8, i * 4, 0x48);
                    }
                    if (item.HP == 0)
                        item.HPPercent = 0;
                    else
                        item.HPPercent = (float)item.HP / item.HPMax;
                    temTeam.Add(item);
                }
            }
            if (temTeam.Count == 0) {
                var item = new TeamMember {
                    Index = 0,
                    ID = NativeMethods.Ri(dwProcessId, Data.JS, Data.JS_OFF_1, Data.JS_NAME),
                    Name = PermaName,
                    HP = TheGamer.HP,
                    HPMax = TheGamer.HPMax
                };

                if (item.HP == 0)
                    item.HPPercent = 0;
                else
                    item.HPPercent = (float)item.HP / item.HPMax;
                item.NwXY.X = TheGamer.JsXY.X;
                item.NwXY.Y = TheGamer.JsXY.Y;
                temTeam.Add(item);
            }
        }
        #endregion

        #region 自动捡物

        /// <summary>
        /// 丢弃物品MAP
        /// </summary>
        public static HashSet<string> DropSet = new HashSet<string>();

        /// <summary>
        /// 地面包裹信息
        /// </summary>
        private static Config<int> floorBagId = new Config<int>("Serializable", "floorBagId", -1);

        /// <summary>
        /// 捡物线程
        /// </summary>
        public void JianwuThread() {
            MsgListener.CommonMsgShow(PermaName, "开启自动捡物……");
            Controler.JWControler = true;
            //如果may的统计量达到了5就确定了 <bagid,count>
            var maybe = new Dictionary<int, int>();
            while (!CoreClosingControler && Controler.JWControler) {
                Thread.Sleep(100);
                if (TheGamer.MapChangeCounter < 30) {
                    continue;
                }
                List<Monster> mlist;
                if (View(out mlist)) {
                    IEnumerable<Monster> ie = from mon in mlist where mon.IsBag orderby mon.HowFar select mon;
                    foreach (Monster mon in ie) {
                        if (mon.MonXy.HowFar(TheGamer.JsXY) < Conf.JianwuDistance.Value) {
                            if (floorBagId.Value < 0) {
                                CheckFloorBagId(mon, ref maybe);
                            }
                            else {
                                Catch(mon.ID);
                                Thread.Sleep(500 + Conf.JianwuCoolDown.Value * 800);
                            }
                        }
                        else if (TheGamer.JsStaticCounter > 30) {
                            if (floorBagId.Value < 0) {
                                CheckFloorBagId(mon, ref maybe);
                            }
                            else {
                                Catch(mon.ID);
                                Thread.Sleep(500 + Conf.JianwuCoolDown.Value * 800);
                            }
                        }
                    }
                    Drop();
                }
            }
            MsgListener.CommonMsgShow(PermaName, "退出自动捡物……");
        }

        /// <summary>
        /// 地面包裹id自动识别
        /// </summary>
        /// <param name="mon"></param>
        /// <param name="maybe"></param>
        private void CheckFloorBagId(Monster mon, ref Dictionary<int, int> maybe) {
            #region 地面包裹询问式确定
            if (NativeMethods.Ri(dwProcessId, Data.FLAG_BAG_FLOOR, Data.FLAG_OFF_1, Data.FLAG_OFF_2, Data.FLAG_OFF_3) == 0) {
                Catch(mon.ID, false);
                for (int i = 0; i < 10; i++) {
                    Thread.Sleep(200);
                    if (NativeMethods.Ri(dwProcessId, Data.FLAG_BAG_FLOOR, Data.FLAG_OFF_1, Data.FLAG_OFF_2, Data.FLAG_OFF_3) == 1) {
                        SendMessageToUi("Id:{0}", mon.TreeObject2);
                        if (maybe.ContainsKey(mon.TreeObject2)) {
                            maybe[mon.TreeObject2]++;
                            if (maybe[mon.TreeObject2] >= 5) {
                                floorBagId.Value = mon.TreeObject2;
                                SendMessageToUi("确定了地面包裹Id");
                            }
                        }
                        else {
                            maybe.Add(mon.TreeObject2, 1);
                        }
                        Catch(mon.ID);
                        break;
                    }
                }
            }
            #endregion
        }

        /// <summary>
        /// 垃圾丢弃
        /// </summary>
        private void Drop() {
            if (!Conf.JianwuDrop.Value || TheGamer.MapChangeCounter < 150)
                return;
            if (DropSet.Count > 0 && NativeMethods.Ri(dwProcessId, Data.FLAG_PASSWORD, Data.FLAG_OFF_1, Data.FLAG_OFF_2, Data.FLAG_OFF_3) == 0) {
                int bagObject = NativeMethods.Ri(dwProcessId, Data.PET, Data.BAG_OFF);
                bool ylq = false;
                for (int i = 0; i < 60; i++) {
                    int off = bagObject + i * 4;
                    if (NativeMethods.Ri(dwProcessId, off, Data.BAG_ID) == i) {
                        string temName = NativeMethods.Rs(dwProcessId, off, Data.BAG_STRING_OFF, Data.BAG_NAME_1, 0);

                        if (string.IsNullOrEmpty(temName)) {
                            temName = NativeMethods.Rs(dwProcessId, off, Data.BAG_STRING_OFF, Data.BAG_NAME_2, 0);
                            if (string.IsNullOrEmpty(temName)) {
                                temName = NativeMethods.Rs(dwProcessId, off, Data.BAG_STRING_OFF, Data.BAG_NAME_3, 0);
                            }
                        }
                        //Console.WriteLine(temName);
                        if (!string.IsNullOrEmpty(temName) && DropSet.Contains(temName)) {
                            if (temName == "愿灵泉" && !ylq) {
                                ylq = true;
                            }
                            else if (TheGamer.MapChangeCounter > 30) {
                                Drop(i);
                                Thread.Sleep(1000);
                            }
                            else {
                                break;
                            }
                        }
                    }
                }
            }
        }
        #endregion

        #region CPU优化设置

        /// <summary>
        /// 优化CPU
        /// </summary>
        public void CpuDown() {
            dm.DownCpu(Conf.CPUDownYN.Value ? Conf.CPUDownPercent.Value : 0);
        }

        #endregion

        #region 挂机类

        /// <summary>
        /// 打怪与状态协调参数
        /// </summary>
        private bool killPause;

        /// <summary>
        /// 打怪线程
        /// </summary>
        private void GuaJiThread() {
            Controler.GJControler = true;
            WorkStateShow(GameState.挂机);

            killPause = true;
            new Task(GuaJiHelpThread).Start();
            while (!CoreClosingControler && Controler.GJControler) {
                Thread.Sleep(10);
                if (TheGamer.Horse || killPause)
                    continue;
                // 环境遍历 -->查找怪
                if (!Conf.KillOneByOneYN.Value || TheGamer.JsStaticCounter > 2) {
                    //非按键模式
                    if (Conf.KillNotAnMode.Value) {
                        if ((TheMenPai.IsJinZhan || Conf.KillOneByOneYN.Value) && TheGamer.JsStaticCounter == 0) {
                            Thread.Sleep(100);
                            continue;
                        }
                        List<Monster> mlist;
                        if (View(out mlist)) {
                            //优先抓取满血怪
                            var fullHpMons = mlist.Where(temMon => temMon.Type == 3 && temMon.Flag > 12 && Math.Abs(temMon.HP - 1) < 0.001)
                                    .OrderBy(temMon => temMon.HowFar);
                            foreach (var fullHpMon in fullHpMons) {
                                KillMonster(fullHpMon);
                                if (TheMenPai.IsJinZhan || Conf.KillOneByOneYN.Value) {
                                    Thread.Sleep(100);
                                    break;
                                }
                            }

                            //抓取血少的怪进行处理
                            if (TheGamer.JsStaticCounter > 0) {
                                var lowestHpMons =
                                    mlist.Where(temMon => temMon.Type == 3 && temMon.Flag > 12 && temMon.HP < 1 && temMon.HP > 0)
                                        .OrderBy(temMon => temMon.HP)
                                        .ThenBy(temMon => temMon.HowFar).ToArray();
                                if (lowestHpMons.Length > 0) {
                                    KillMonster(lowestHpMons[0]);
                                }
                            }
                        }
                    }
                    else {
                        dm.KeyPressChar(Conf.KillSelectKey.Value);
                        Thread.Sleep(150);
                        dm.KeyPressChar("F1");
                        Thread.Sleep(150);
                    }
                }
                //调用按键技能
                if (Conf.KillSkillYN.Value && TheGamer.State == 7) {
                    var theReleaseSkills = KillMonData.GetAvailableSkills();
                    for (int i = 0; i < theReleaseSkills.Count; i++) {
                        dm.KeyPressChar(theReleaseSkills[i].Name);
                        Thread.Sleep(300);
                        theReleaseSkills[i].LastReleaseTime = DateTime.Now;
                        if (i > 2)
                            break;
                    }
                }
            }
            WorkStateShow(GameState.空闲);
        }

        /// <summary>
        /// 内存打怪执行函数
        /// </summary>
        /// <param name="monster"></param>
        private void KillMonster(Monster monster) {
            Skill_JS(TheMenPai.FirstSkill.SkillID, monster.ID);
            float ct = (TheMenPai.IsJinZhan ? 50 + 4 * monster.HowFar : 16);
            for (int i = 0; i < ct; i++) {
                if (i > 10 && NativeMethods.Rf(dwProcessId, monster.TreeObject2 + 8) < monster.HP) {
                    break;
                }
                Thread.Sleep(10);
            }
        }

        /// <summary>
        /// 挂机辅助线程
        /// 监控挂机地图 血 等状态
        /// </summary>
        private void GuaJiHelpThread() {
            GuaJiDian[] temDians = null;
            DateTime lsChange = DateTime.Now.AddMinutes(-5);
            int luId = 0;
            while (!CoreClosingControler && Controler.GJControler) {
                Thread.Sleep(100);
                if (TheGamer.MapChangeCounter < 30)
                    continue;
                if (Conf.KillAutoBackYN.Value) {
                    if (Conf.KillFullMonYN.Value && Conf.KillFullMonCount.Value <= TheGamer.MonKilled) {
                        if (TheGamer.MapName != "洛阳") {
                            Walk("洛阳");
                        }
                        else {
                            Controler.GJControler = false;
                            Thread.Sleep(2000);
                            mainThread.ContinueWith(delegate {
                                DoNextTask(Conf.KillNextTask.Value);
                            });
                        }
                        //超怪处理
                        continue;
                    }
                    if (string.IsNullOrEmpty(Conf.KillAutoBackMapName.Value))
                        Conf.KillAutoBackMapName.Value = TheGamer.MapName;
                    if (TheGamer.MapName != Conf.KillAutoBackMapName.Value) {
                        killPause = true;
                        if (Conf.KillFullHPYN.Value && TheGamer.HPMax * 0.8 > TheGamer.HP) {
                            if (TheGamer.MapName != "洛阳")
                                Walk("洛阳");
                            else
                                LuoYangHealth();
                        }
                        else {
                            if (!TheGamer.Horse) {
                                HorseOperate(true);
                                Thread.Sleep(300);
                            }
                            Walk(Conf.KillAutoBackMapName.Value);
                        }
                    }
                    else if (temDians == null) {
                        temDians = KillMonData.GetGuaDiansByMap(Conf.KillAutoBackMapName.Value, TheGamer.JsXY);
                        if (temDians.Length == 0) {
                            var temDian = new GuaJiDian { Cd = 30, GuaJiXy = TheGamer.JsXY, Map = TheGamer.MapName };
                            temDians = new[] { temDian };
                        }
                    }
                    else if ((DateTime.Now - lsChange).TotalSeconds > temDians[luId].Cd) {
                        if (TheGamer.MapName == temDians[luId].Map) {
                            if ((DateTime.Now - lsChange).TotalSeconds > temDians[luId].Cd + 10 || TheGamer.JsStaticCounter > 5) {
                                luId = (++luId) % temDians.Length;
                                killPause = true;
                                if (TheGamer.JsXY.HowFar(temDians[luId].GuaJiXy) > 20) {
                                    HorseOperate(true);
                                }
                                WalkToXy(temDians[luId].GuaJiXy);
                                Thread.Sleep(100);
                                HorseOperate(false);
                                lsChange = DateTime.Now;
                                killPause = false;
                            }
                        }
                        else {
                            temDians = null;
                        }
                    }
                    else if (Conf.KillFullHPYN.Value && TheGamer.HPMax * 0.01 > TheGamer.HP) {
                        killPause = true;
                        Walk("洛阳");
                    }
                }
                else {
                    if (killPause)
                        killPause = false;
                    Thread.Sleep(500);
                }
            }
        }

        /// <summary>
        /// 开启下个任务
        /// </summary>
        /// <param name="taskName"></param>
        private void DoNextTask(string taskName) {
            ThreadMethods next;
            if (Enum.TryParse(taskName, out next)) {
                switch (next) {
                    case ThreadMethods.和尚反贼:
                    case ThreadMethods.箱子棋局:
                        BuildTask(ThreadMethods.和尚反贼, null);
                        break;
                    default:
                        BuildTask(next, null);
                        break;
                }
            }
        }

        /// <summary>
        /// 洛阳回血函数
        /// </summary>
        private void LuoYangHealth() {
            if (TheGamer.MapName != "洛阳") {
                return;
            }
            if (TheGamer.JsXY.HowFar(184, 334) < 3) {
                if (TheGamer.JsStaticCounter > 3) {
                    var npc = new Monster();
                    if (GetNpc("龙霸天", ref npc)) {
                        WalkToXy(npc.MonXy);
                        Thread.Sleep(200);
                        if (TalkNpc(npc.ID, "满怒治疗")) {
                            Thread.Sleep(1000);
                            TalkNpc("是");
                            Thread.Sleep(1000);
                        }
                    }
                }
            }
            else {
                WalkToXy(184f, 334f);
            }
        }
        #endregion

        #region 箱子棋局

        /// <summary>
        /// 箱子棋局线程
        /// </summary>
        private void XiangZiQiJuThread() {
            string[] maps = { "楼兰藏宝洞", "牡丹碗", "珍珑棋局" };
            string theMap = TheGamer.MapName;
            if (string.IsNullOrEmpty(theMap) || !maps.Contains(theMap)) {
                MsgListener.MsgBoxMsgShow("请在副本地图内启动任务！", "副本提示");
                return;
            }
            while (!CoreClosingControler && TheGamer.MapChangeCounter < 30)
                Thread.Sleep(200);
            Controler.XQControler = true;
            switch (theMap) {
                case "楼兰藏宝洞":
                    WorkStateShow(GameState.箱子);
                    break;
                case "牡丹碗":
                    WorkStateShow(GameState.蹴鞠);
                    break;
                case "珍珑棋局":
                    WorkStateShow(GameState.棋局);
                    break;
            }

            CreateFbKillThread();
            var nextXy = new XY();
            bool boss = false;
            int monCount = 0, bagCount = 0;
            var npc = new Monster();
            int bossDeadCheck = 0;
            for (int i = 0; i < 5; i++) {
                if (TheGamer.Horse) {
                    dm.DmKeyPress("f", 5);
                    HorseOperate(false);
                }
                else {
                    break;
                }
                Thread.Sleep(2000);
            }
            dm.DmKeyPress("f", 5);
            while (!CoreClosingControler && Controler.XQControler) {
                if (!string.IsNullOrEmpty(TheGamer.MapName) && TheGamer.MapName != theMap) {
                    if (theMap == "珍珑棋局")
                        Conf.FBlsQiJu.Value = DateTime.Now.Date.ToFileTime();
                    else if (theMap == "楼兰藏宝洞")
                        Conf.FBlsXiangZi.Value = DateTime.Now.Date.ToFileTime();
                    //Debug.WriteLine("记录时间然后退出");
                    Controler.FKControler = false;
                    Controler.XQControler = false;
                    break;
                }
                Thread.Sleep(200);
                List<Monster> mlist;
                if (View(out mlist)) {
                    IEnumerable<Monster> ie;
                    if (!boss) {
                        ie = mlist.Where(temMon => temMon.Type == 3 && temMon.Flag > 12 && temMon.HP > 0)
                          .OrderByDescending(temMon => temMon.HowFar);
                        foreach (Monster mon in ie) {
                            nextXy = mon.MonXy;
                            break;
                        }
                        //对棋局的补充
                        if (mlist.Count(tem => tem.Name == "远古棋魂" && tem.Type == 3 && tem.Flag > 0) > 0)
                            boss = true;
                    }
                    if (!Controler.JWControler && (boss || theMap == "牡丹碗")) {
                        ie = mlist.Where(temMon => temMon.IsBag).OrderBy(temMon => temMon.HowFar);
                        foreach (Monster mon in ie) {
                            if (mon.HowFar < 5)
                                Catch(mon.ID);
                            else if (TheGamer.JsStaticCounter > 10)
                                Catch(mon.ID);
                            Thread.Sleep(800);
                        }
                        Drop();
                    }
                    monCount = mlist.Count(mon => mon.Type == 3 && mon.Flag > 12 && mon.HP > 0);
                    if (boss)
                        bagCount = mlist.Count(temMon => temMon.IsBag);

                }

                //检查挂机状态
                if (!boss) {
                    string stateMsg = GetTaskMsg();
                    if (stateMsg.Contains("200/200") || stateMsg.Contains("199/199")) {
                        boss = true;
                        if (theMap == "楼兰藏宝洞") {
                            Thread.Sleep(10000);
                            nextXy.X = 62f;
                            nextXy.Y = 78f;
                            WalkToXy(nextXy);
                        }
                    }
                }
                else if (theMap == "珍珑棋局" && TheGamer.JsStaticCounter > 30 && monCount == 0 && bagCount == 0 && bossDeadCheck++ > 30) {
                    WalkToXy(40f, 40f);//
                    if (GetNpc("齐圣", ref npc)) {
                        TalkNpc(npc.ID, "确定");
                        Thread.Sleep(5000);
                    }
                }
                if (monCount == 0 && !boss && TheGamer.MapName == theMap && nextXy.Islegal() && nextXy.HowFar(TheGamer.JsXY) > 5 && TheGamer.JsStaticCounter > 10) {
                    if (TheGamer.JsStaticCounter > 10 && nextXy.Islegal() && TheGamer.JsXY.HowFar(nextXy) > 8) {
                        Walk(nextXy);
                        Thread.Sleep(500);
                    }
                    Thread.Sleep(500);
                }
            }
            WorkStateShow(GameState.空闲);
        }

        /// <summary>
        /// 副本暂停打怪控制器
        /// </summary>
        private bool _fbPause;

        private void StopFbKillThread() {
            Controler.FKControler = false;
            _fbPause = false;
        }

        /// <summary>
        /// 副本打怪线程
        /// </summary>
        private void FbKillThread() {
            Controler.FKControler = true;
            while (!CoreClosingControler && Controler.FKControler) {
                Thread.Sleep(150);
                if (_fbPause || TheGamer.Horse)
                    continue;
                if ((!TheMenPai.IsJinZhan && TheMenPai.MyMenPai != MenPaiSet.峨眉) || TheGamer.JsStaticCounter > 5) {
                    dm.KeyPressChar(Conf.KillSelectKey.Value);
                    Thread.Sleep(100);
                    dm.KeyPressChar("F1");
                    Thread.Sleep(150);
                }

                if (TheGamer.State == 7) {
                    var theReleaseSkills = KillMonData.GetAvailableSkills();
                    for (int i = 0; i < theReleaseSkills.Count && i < 3; i++) {
                        dm.KeyPressChar(theReleaseSkills[i].Name);
                        Thread.Sleep(500);
                        theReleaseSkills[i].LastReleaseTime = DateTime.Now;
                    }
                }
            }
        }
        #endregion

        #region 和尚反贼

        /// <summary>
        /// 和尚反贼线程函数体
        /// </summary>
        private void HsFzThread() {
            var temTaskInfo = new FbTaskInfo();
            bool leader = false;
            Controler.HFControler = true;
            DateTime lsCaiJiTime = DateTime.Now.AddHours(-1);
            WorkStateShow(GameState.副本);
            while (!CoreClosingControler && Controler.HFControler) {
                Thread.Sleep(50);
                if (MatchTask(ref temTaskInfo)) {
                    if (TheGamer.MapName == temTaskInfo.InnerMap) {
                        if (temTaskInfo.TheFbName == FbState.棋局 || temTaskInfo.TheFbName == FbState.箱子) {
                            XiangZiQiJuThread();
                            WorkStateShow(GameState.副本);
                        }
                        else {
                            FinishThisFb(temTaskInfo);
                        }
                    }
                    else if (TheGamer.MapName == temTaskInfo.OuterMap) {
                        if (FbTeamCheck(ref leader, false) && leader) {
                            SearchNpc(ref temTaskInfo, ref leader);
                        }
                    }
                    else {
                        Walk(temTaskInfo.OuterMap);
                    }
                }
                else {
                    FbHaveRest(ref lsCaiJiTime);//暂时没有处理任务
                    Thread.Sleep(200);
                }
            }
            WorkStateShow(GameState.空闲);
        }

        /// <summary>
        /// 副本休息方案
        /// </summary>
        /// <param name="lsCaiJiTime">采集时间控制</param>
        private void FbHaveRest(ref DateTime lsCaiJiTime) {
            //满足启动条件
            if (Conf.HFCJ.Value && TheGamer.Energy > 250 && HasEmptyBag(1) && (DateTime.Now - lsCaiJiTime).TotalHours >= 1) {
                dm.DmKeyPress("f", 5);
                Thread.Sleep(100);
                CaiJiMainThread();
                WorkStateShow(GameState.副本);
                lsCaiJiTime = DateTime.Now;
            }
            else if (TheGamer.MapName != "洛阳") {
                dm.DmKeyPress("f", 5);
                Thread.Sleep(100);
                Walk("洛阳");
            }
        }

        /// <summary>
        /// 副本NPC搜索
        /// </summary>
        /// <param name="temTaskInfo">副本任务信息</param>
        /// <param name="leader">队长标记</param>
        private void SearchNpc(ref FbTaskInfo temTaskInfo, ref bool leader) {
            if (TheGamer.MapChangeCounter < 30)
                return;
            bool hasGetted = false;
            var npc = new Monster();
            while (TheGamer.MapName == temTaskInfo.OuterMap && !CoreClosingControler && Controler.HFControler) {
                Thread.Sleep(50);
                if (!hasGetted) {
                    if (!MatchTask(ref temTaskInfo))
                        return;
                    //Debug.WriteLine("副本匹配");
                    if (GetNpc(temTaskInfo.OuterNpc, ref npc)) {
                        WalkToXy(npc.MonXy);
                        hasGetted = true;
                        //Debug.WriteLine("发现NPC");
                    }
                    if (!hasGetted) {
                        if (TheGamer.JsXY.HowFar(temTaskInfo.OuterLu[temTaskInfo.OuterLuId]) < 3) {
                            temTaskInfo.OuterLuId = ++temTaskInfo.OuterLuId % temTaskInfo.OuterLu.Count;
                            if (temTaskInfo.OuterLuId == temTaskInfo.OuterLu.Count - 1) {
                                temTaskInfo.SearchTime++;
                            }
                        }
                        if (TheGamer.JsStaticCounter > 5 || TheGamer.State == 2 && _tarXy != temTaskInfo.OuterLu[temTaskInfo.OuterLuId]) {
                            Walk(temTaskInfo.OuterLu[temTaskInfo.OuterLuId]);
                            Thread.Sleep(500);
                        }
                        //作为队长变化了
                        if (FbTeamCheck(ref leader, true) && !leader)
                            return;
                        //任务变化直接返回
                    }
                }
                else if (FbTeamCheck(ref leader, true)) {
                    //Debug.WriteLine("对话NPC");
                    if (!leader)
                        return;
                    if (TalkNpc(npc.ID, temTaskInfo.OuterDia))
                        Thread.Sleep(4000);
                    Thread.Sleep(1000);
                    hasGetted = false;
                }
            }
        }

        /// <summary>
        /// 队伍状态检查
        /// </summary>
        /// <param name="leader">队长标记</param>
        /// <param name="justCheck">只查询是否是队长</param>
        /// <returns></returns>
        private bool FbTeamCheck(ref bool leader, bool justCheck) {
            if (TheGamer.MapChangeCounter < 30)
                return false;

            var temTeam = new List<TeamMember>();
            TeamView(ref temTeam);

            //对队伍信息的判定加强
            if (temTeam.Count > 1 && temTeam.Count(tem => tem.Index == 0 && tem.Name == PermaName) == 1)
                leader = true;
            else
                leader = false;
            if (justCheck || temTeam.Count == 1)
                return true;

            if (leader) {
                int i = temTeam.Count(tem => tem.Index > 0 && (!tem.NwXY.Islegal() || tem.HP < 0 || tem.NwXY.HowFar(TheGamer.JsXY) > 7));
                //Debug.WriteLine("集合状态不满足成员数:{0}", i);
                if (i > 0)
                    return false;
                //进入跟随
                dm.DmKeyPress("e", 5);
                return true;
            }
            //队长尚未到达地图
            if (temTeam[0].HP < 0 || !temTeam[0].NwXY.Islegal())
                return false;
            //比对队长位置
            if (TheGamer.JsXY.HowFar(temTeam[0].NwXY) > 7 &&
                TheGamer.JsStaticCounter > 100 &&
                TheGamer.MapChangeCounter > 50) {
                dm.DmKeyPress("f", 5);
                WalkToXy(temTeam[0].NwXY);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 副本内完成操作
        /// </summary>
        /// <param name="temTaskInfo"></param>
        private void FinishThisFb(FbTaskInfo temTaskInfo) {
            if (TheGamer.MapName != temTaskInfo.InnerMap)
                return;
            Thread.Sleep(1000);
            while (TheGamer.JsStaticCounter < 10 || TheGamer.MapChangeCounter < 30)
                Thread.Sleep(100);
            temTaskInfo.InnerLuId = 0;
            dm.DmKeyPress("f", 5);//退出跟随状态
            var npc = new Monster();
            var leader = false;

            var monIdSet = new HashSet<int>();

            if (temTaskInfo.TheFbName == FbState.和尚) {
                if (FbTeamCheck(ref leader, true) && leader) {
                    if (!GetNpc("少林云游武僧", ref npc)) {
                        if (TheGamer.MapName == temTaskInfo.InnerMap) {
                            WalkToXy(temTaskInfo.InnerLu[temTaskInfo.InnerLuId]);
                            Thread.Sleep(200);
                        }
                        return;
                    }
                    WalkToXy(npc.MonXy);
                    for (int i = 0; i < 3; i++) {
                        if (TalkNpc(npc.ID, temTaskInfo.InnerDia)) {
                            Thread.Sleep(500);
                            break;
                        }
                        Thread.Sleep(1000);
                    }
                }

            }
            CreateFbKillThread();
            bool boss = false;//进入BOSS环节
            bool bossDeath = false;//判定BOSS已经死亡
            int noMonCheck = 0;
            DateTime tGetIn = DateTime.Now;
            //HashSet<string> HSMSG = new HashSet<string>();
            while (Controler.HFControler && !CoreClosingControler) {
                Thread.Sleep(200);
                if (!string.IsNullOrEmpty(TheGamer.MapName) && TheGamer.MapName != temTaskInfo.InnerMap) {
                    Controler.FKControler = false;
                    break;
                }
                List<Monster> mlist;
                if (View(out mlist)) {
                    if (!boss) {
                        //检查BOSS
                        if (mlist.Count(tem => tem.Type == 3 && tem.Flag > 12 && tem.Name == temTaskInfo.BossName) > 0) {
                            boss = true;
                            continue;
                        }

                        if (temTaskInfo.InnerLu[temTaskInfo.InnerLuId].HowFar(TheGamer.JsXY) < 3) {
                            temTaskInfo.InnerLuId = ++temTaskInfo.InnerLuId % temTaskInfo.InnerLu.Count;
                            _fbPause = false;
                        }

                        if (mlist.Count(tem => tem.HP > 0 && tem.Type == 3 && tem.Flag > 12 && !string.IsNullOrEmpty(tem.Name)) > 0) {
                            foreach (Monster temMon in mlist.Where(tem => !monIdSet.Contains(tem.ID) && tem.Type == 3 && tem.Flag > 12 && tem.HP > 0)) {
                                monIdSet.Add(temMon.ID);
                            }
                            noMonCheck = 0;
                        }
                        else {
                            noMonCheck++;
                            if (noMonCheck > 5) {
                                _fbPause = true;
                                WalkToXy(temTaskInfo.InnerLu[temTaskInfo.InnerLuId]);
                                Thread.Sleep(200);
                                HorseOperate(false);
                            }
                        }
                        string temMsg = GetTaskMsg();
                        if (temTaskInfo.TheFbName == FbState.反贼) {
                            if (temMsg.Contains("30/31") || temMsg.Contains("31/31"))
                                boss = true;
                        }
                        else if ((monIdSet.Count > 125 && noMonCheck > 10) || temMsg.Contains("CJG_090413_24")) {
                            boss = true;
                        }
                        else if (!temMsg.Contains("CJG_090413_32")) {
                            tGetIn = DateTime.Now;
                            if (noMonCheck > 5 * 50)
                                boss = true;
                        }
                        else if (noMonCheck > 20 && (DateTime.Now - tGetIn).TotalSeconds > 45) {
                            boss = true;
                        }
                        //对场景内的状态进行识别
                    }
                    else if (!bossDeath) {
                        //对场景内的状态进行识别-->离开场景倒计时出现之后就表明击杀完成了-->
                        if (TheGamer.JsStaticCounter > 10) {
                            XY temXy = temTaskInfo.TheFbName == FbState.和尚 ? new XY(59f, 31f) : temTaskInfo.InnerLu[temTaskInfo.InnerLu.Count - 1];
                            if (TheGamer.JsXY.HowFar(temXy) > 7) {
                                _fbPause = true;
                                WalkToXy(temXy);
                                _fbPause = false;
                            }
                        }
                        if (mlist.Count(tem => Math.Abs(tem.HP) < 0.001 && tem.Name == temTaskInfo.BossName && tem.ID > 0) == 1) {
                            bossDeath = true;
                            noMonCheck = 0;
                        }
                    }
                    else {
                        HorseOperate(true);
                        // 出去
                        if (temTaskInfo.TheFbName == FbState.和尚 && mlist.Count(tem => tem.IsBag) == 0 && noMonCheck++ > 10) {
                            WalkToXy(70f, 18f);
                            Thread.Sleep(2000);
                        }
                    }

                    if (!Controler.JWControler && (bossDeath || temTaskInfo.TheFbName == FbState.反贼)) {
                        IEnumerable<Monster> iem = mlist.Where(tem => tem.IsBag).OrderBy(tem => tem.HowFar);
                        foreach (Monster mon in iem) {
                            if (mon.MonXy.HowFar(TheGamer.JsXY) < 3)
                                Catch(mon.ID);
                            else if (TheGamer.JsStaticCounter > 20)
                                Catch(mon.ID);
                            Thread.Sleep(800);
                        }
                        Drop();
                    }
                }
            }
        }

        /// <summary>
        /// 获取任务信息
        /// </summary>
        /// <returns></returns>
        internal string GetTaskMsg() {
            return NativeMethods.Rs(dwProcessId, Data.CALL_NPCDIA, 68, 2);
        }

        /// <summary>
        /// 由时辰来匹配任务
        /// </summary>
        /// <param name="temTaskInfo">任务信息类</param>
        /// <returns></returns>
        private bool MatchTask(ref FbTaskInfo temTaskInfo) {
            int hour = DateTime.Now.Hour, minute = DateTime.Now.Minute;
            var temFbName = FbState.休息;
            if (TheGamer.MapName == "珍珑棋局")
                temFbName = FbState.棋局;
            else if (TheGamer.MapName == "楼兰藏宝洞")
                temFbName = FbState.箱子;
            else if (Conf.HsYN.Value && (((hour == 10 && minute > 43) || (hour == 11 && minute < 15)) || (hour == 16 && minute > 27) || (hour == 21 && minute > 28) || (hour == 23 && minute < 30))) {
                temFbName = FbState.和尚;
                //和尚时间
            }
            else if (Conf.FzYN.Value && (hour == 2 || hour == 13 || hour == 15 || hour == 17 || hour == 19 || hour == 21)) {
                temFbName = FbState.反贼;
                //是反贼时间
            }
            else if ((hour == 11 && minute > 29) || hour == 12 || hour == 20 || hour == 21) {
                long today = DateTime.Now.Date.ToFileTime();
                //优先刷棋局
                if (Conf.FBlsQiJu.Value != today && !(hour == 20 && minute < 30)) {
                    temFbName = FbState.棋局;
                }
                else if (today != Conf.FBlsXiangZi.Value && TheGamer.Level >= 75) {
                    temFbName = FbState.箱子;
                }
            }

            //Debug.WriteLine("当前副本匹配为：{0},原始副本为:{1}", temFbName, temTaskInfo.TheFbName);

            if (temFbName == FbState.休息) {
                temTaskInfo.SearchTime = 0;
                return false;
            }

            if (temTaskInfo.TheFbName == temFbName) {
                if (temTaskInfo.SearchTime > 2) {
                    return false;
                }
                return true;
            }

            switch (temFbName) {
                case FbState.反贼:
                    GetFz(out temTaskInfo);
                    break;
                case FbState.和尚:
                    GetHs(out temTaskInfo);
                    break;
                case FbState.棋局:
                    GetQj(out temTaskInfo);
                    return true;
                case FbState.箱子:
                    GetXz(out temTaskInfo);
                    return true;
                default:
                    return false;
            }
            if (temTaskInfo.InnerLu != null && temTaskInfo.OuterLu != null)
                return true;
            return false;
        }

        /// <summary>
        /// 箱子副本信息
        /// </summary>
        /// <param name="temTaskInfo"></param>
        private void GetXz(out FbTaskInfo temTaskInfo) {
            temTaskInfo = new FbTaskInfo {
                TheFbName = FbState.箱子,
                OuterLuId = 0,
                InnerMap = "楼兰藏宝洞",
                OuterMap = "楼兰",
                OuterLu = new List<XY> { new XY(162f, 76f) },
                OuterDia = "楼兰寻宝",
                OuterNpc = "金久灵"
            };
            //寻路
            //进副本
        }

        /// <summary>
        /// 棋局副本信息
        /// </summary>
        /// <param name="temTaskInfo"></param>
        private void GetQj(out FbTaskInfo temTaskInfo) {
            temTaskInfo = new FbTaskInfo {
                TheFbName = FbState.棋局,
                OuterLuId = 0,
                InnerMap = "珍珑棋局",
                OuterMap = "洛阳",
                OuterLu = new List<XY> { new XY(365f, 228f) },
                OuterDia = "珍珑棋局",
                OuterNpc = "王积薪"
            };
            //寻路
            //进副本
        }

        /// <summary>
        /// 和尚副本信息
        /// </summary>
        /// <param name="temTaskInfo"></param>
        private void GetHs(out FbTaskInfo temTaskInfo) {
            temTaskInfo = new FbTaskInfo {
                TheFbName = FbState.和尚,
                OuterLuId = 0,
                InnerLuId = 0,
                InnerMap = "藏经阁",
                OuterMap = Conf.HsMap.Value
            };
            //寻路
            temTaskInfo.OuterLu = GetLu(temTaskInfo.OuterMap);
            temTaskInfo.InnerLu = GetLu(temTaskInfo.InnerMap);
            //进副本
            temTaskInfo.OuterDia = "CJG_090413_08";//对话进入副本
            temTaskInfo.InnerDia = "CJG_090413_18";//开启副本
            temTaskInfo.OuterNpc = "少林云游武僧";
            //完成判定
            temTaskInfo.BossName = "蒙面恶僧";
        }

        /// <summary>
        /// 反贼副本信息
        /// </summary>
        /// <param name="temTaskInfo"></param>
        private void GetFz(out FbTaskInfo temTaskInfo) {
            temTaskInfo = new FbTaskInfo {
                TheFbName = FbState.反贼,
                OuterLuId = 0,
                InnerLuId = 0,
                InnerMap = "贼寇营地",
                OuterMap = Conf.FzMap.Value
            };
            //寻路
            temTaskInfo.OuterLu = GetLu(temTaskInfo.OuterMap);
            temTaskInfo.InnerLu = GetLu(temTaskInfo.InnerMap);
            //进副本
            temTaskInfo.OuterDia = "难道我还怕你不成";
            temTaskInfo.OuterNpc = "造反恶贼";
            //完成判定
            temTaskInfo.BossName = "贼兵头目";
        }


        /// <summary>
        /// 由地图名解析路径信息
        /// </summary>
        /// <param name="map">地图名字</param>
        /// <returns>返回路径有序链表</returns>
        private List<XY> GetLu(string map) {
            var luPath = new List<XY>();
            string fileName = string.Format("./system/{0}.txt", map);
            if (ZuoBiao(fileName, ref luPath)) {
                return luPath;
            }
            return null;
        }
        #endregion

        #region 钓鱼
        /// <summary>
        /// 钓鱼线程
        /// </summary>
        private void DyThread() {
            XY dyXy;
            switch (Conf.DYMap.Value) {
                case "剑阁":
                    dyXy = new XY(86, 219);
                    break;
                case "洱海":
                    dyXy = new XY(252, 197);
                    break;
                case "苍山":
                    dyXy = new XY(225, 75);
                    break;
                case "石林":
                    dyXy = new XY(272, 119);
                    break;
                case "高昌":
                    dyXy = new XY(105, 69);
                    break;
                case "雁南":
                    dyXy = new XY(195, 184);
                    break;
                case "雁北":
                    dyXy = new XY(64, 222);
                    break;
                case "草原":
                    dyXy = new XY(221, 173);
                    break;
                case "西湖":
                    dyXy = new XY(131, 94);
                    break;
                case "龙泉":
                    dyXy = new XY(43, 215);
                    break;
                case "武夷":
                    dyXy = new XY(103, 237);
                    break;
                default:
                    MsgListener.MsgBoxMsgShow("钓鱼不支持当前地图", "钓鱼地图错误");
                    return;
            }
            Controler.DYControler = true;
            WorkStateShow(GameState.钓鱼);
            MsgListener.CommonMsgShow(PermaName, "开启钓鱼模式!");
            while (!CoreClosingControler && Controler.DYControler) {
                Thread.Sleep(200);
                if (HasEmptyBag(1)) {
                    if (TheGamer.MapName != Conf.DYMap.Value) {
                        Walk(Conf.DYMap.Value);
                        Thread.Sleep(1000);
                    }
                    else if (TheGamer.MapChangeCounter > 50 && TheGamer.JsStaticCounter > 30) {
                        if (dyXy.HowFar(TheGamer.JsXY) > 2) {
                            WalkToXy(dyXy);
                            Thread.Sleep(500);
                            HorseOperate(false);
                            Thread.Sleep(100);
                        }
                        Monster fish = GetFish();
                        if (fish != null) {
                            WalkToXy(fish.MonXy);
                            Thread.Sleep(500);
                            Catch(fish.ID);
                            Thread.Sleep(500);
                        }
                    }
                }
                else if (Conf.DYSellYN.Value) {
                    if (TheGamer.MapName != "洛阳") {
                        while (TheGamer.State == 8 && !CoreClosingControler)
                            RandomWalk();
                        Walk("洛阳", true, 348f, 285f);
                    }
                    else if (TheGamer.JsXY.HowFar(348f, 285f) > 2) {
                        WalkToXy(348f, 285f);
                        Thread.Sleep(200);
                    }
                    else if (NativeMethods.Ri(dwProcessId, Data.FLAG_PASSWORD, Data.FLAG_OFF_1, Data.FLAG_OFF_2, Data.FLAG_OFF_3) == 0) {
                        var sailNpc = new Monster();
                        if (GetNpc("芮福祥", ref sailNpc)) {
                            if (TalkNpc(sailNpc.ID, "买卖杂货")) {
                                List<GamerBag> gameBags;
                                ViewMyBag(out gameBags, 30, 60);
                                var sellist = (from tem in gameBags where tem.Sort.Contains("级鱼类") select tem.ID).ToList();
                                UseBag(sellist);
                            }
                        }
                    }
                }
            }
            MsgListener.CommonMsgShow(PermaName, "退出钓鱼模式!");
            WorkStateShow();
        }

        /// <summary>
        /// 获取鱼类信息
        /// </summary>
        /// <returns></returns>
        private Monster GetFish() {
            List<Monster> mlist;
            if (View(out mlist)) {
                return mlist.Where(t => t.Type == 8 && t.Name.Contains("鱼")).OrderBy(t => t.HowFar).FirstOrDefault();
            }
            return null;
        }
        #endregion

        #region 许愿

        /// <summary>
        /// 到任务接受或完成的地图去
        /// </summary>
        /// <param name="tarMap"></param>
        /// <param name="tarPosition"></param>
        /// <returns></returns>
        private bool GotoMessionMap(string tarMap, XY tarPosition) {
            if (TheGamer.MapName != tarMap) {
                Walk(tarMap);
                return false;
            }
            WalkToXy(tarPosition);
            if (tarPosition.HowFar(TheGamer.JsXY) > 2) {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 许愿任务执行线程
        /// </summary>
        private void XuYuanThreadFunc() {
            Controler.XYControler = true;
            WorkStateShow(GameState.许愿);
            //苏州接受任务NPC的坐标
            var liangDaoShi = new XY(282, 276);
            var nwState = XuYuanState.None;
            while (!CoreClosingControler && Controler.XYControler) {
                switch (nwState) {
                    case XuYuanState.None:
                        #region 到任务NPC处 将任务状态置为接受
                        if (GotoMessionMap("苏州", liangDaoShi)) {
                            if (AcceptOrFinishXuYuan(nwState)) {
                                nwState = XuYuanState.Accept;
                            }
                        }
                        #endregion
                        break;
                    case XuYuanState.Accept:
                        #region 去太湖许愿 并且在完成之后将状态置换为提交
                        //去任务目标地
                        if (CompleteXuYuan()) {
                            nwState = XuYuanState.Finish;
                        }
                        #endregion
                        break;
                    case XuYuanState.Finish:
                        #region 提交完成 退出线程
                        if (GotoMessionMap("苏州", liangDaoShi)) {
                            if (AcceptOrFinishXuYuan(nwState)) {
                                Controler.XYControler = false;
                            }
                        }
                        #endregion
                        break;
                }
                Thread.Sleep(200);
            }
            WorkStateShow(GameState.空闲);
        }

        /// <summary>
        /// 在太湖许愿
        /// </summary>
        /// <returns></returns>
        private bool CompleteXuYuan() {
            var ylq = new List<int>();
            int retry = 10;
            //太湖许愿树的坐标
            var xuYuanShu = new XY(160, 186);
            while (retry > 0 && !CoreClosingControler && Controler.XYControler) {
                if (GotoMessionMap("太湖", xuYuanShu)) {
                    if (TheGamer.JsStaticCounter > 10) {
                        if (TheGamer.Horse)
                            HorseOperate(false);
                        UseBag("愿灵泉", start: 0, end: 30);
                        //List<GamerBag> bags;
                        //ViewMyBag(out bags, 0, 30);
                        //ylq.Clear();
                        //ylq.AddRange(from tmp in bags where tmp.Name == "愿灵泉" select tmp.ID);
                        //if (ylq.Count > 0)
                        //{
                        //    UseBag(ylq);
                        //}
                        retry--;
                    }
                    else if (TheGamer.State == 5) {
                        retry = 10;
                    }
                }
                Thread.Sleep(500);
            }
            return true;
        }

        /// <summary>
        /// 接受或提交许愿任务
        /// </summary>
        /// <returns></returns>
        private bool AcceptOrFinishXuYuan(XuYuanState state) {
            var npc = new Monster();
            //对话接受1001个愿望
            if (GetNpc("梁道士", ref npc) && TalkNpc(npc.ID, "SQXY_09061_4")) {
                Thread.Sleep(1000);
                //检查任务状态
                var tem = MessionState.未知;
                int retry = 5;
                while (retry > 0 && !CoreClosingControler && Controler.XYControler) {
                    if (AcceptOrFinish(ref tem)) {
                        switch (tem) {
                            case MessionState.继续完成:
                            case MessionState.完成:
                                if (state == XuYuanState.Finish)
                                    return true;
                                return false;
                            default:
                                if (state == XuYuanState.None)
                                    return true;
                                return false;
                        }
                    }
                    retry--;
                    Thread.Sleep(500);
                }
                return true;
            }
            return false;
        }
        #endregion

        #region Dispose
        /// <summary>
        /// 关闭打开的线程等资源
        /// </summary>
        public void Close() {
            //将所有的线程开关关闭
            CoreClosingControler = true;
            Controler.Close();
            if (dm != null)
                dm.Dispose();
        }
        #endregion

        #region 刷猪

        /// <summary>
        /// 圣兽山野猪统一控制
        /// </summary>
        private static bool _nonePig;
        /// <summary>
        /// 刷猪主线程
        /// </summary>
        internal void PigThread() {
            WorkStateShow(GameState.野猪);
            //刷猪控制参数
            Controler.PGControler = true;
            //圣兽山坐标
            var searchLu = GetLu("圣兽山");
            var luId = 2;
            _nonePig = false;
            while (!CoreClosingControler && Controler.PGControler) {
                //循环搜索第二次没有找到可以返回大理了
                if (_nonePig) {
                    Controler.PGControler = false;
                    ReturnDaLi();
                    continue;
                }
                Thread.Sleep(200);
                var nwMap = TheGamer.MapName;
                if (string.IsNullOrEmpty(nwMap)) {
                    continue;
                }
                switch (nwMap) {
                    case "圣兽山副本":
                        FinishSssfb();
                        break;
                    case "圣兽山":
                        SearchAndWaitforGetInFb(searchLu, ref luId);
                        break;
                    default:
                        GotoShengshouShan();
                        break;
                }
            }
            WorkStateShow(GameState.空闲);
        }

        /// <summary>
        /// 刷猪任务检查完成后自动出副本
        /// </summary>
        internal static Config<bool> AutoGetOutOfShengShouShanFb = new Config<bool>("./common.cfg", "ShengShouShanFB/AutoGetOut", false);

        /// <summary>
        /// 完成圣兽山副本
        /// </summary>
        private void FinishSssfb() {
            CreateFbKillThread();
            var hasFinish = false;
            List<Monster> mlist;
            Thread.Sleep(2000);
            for (int iTimer = 0; iTimer < 100; iTimer++) {
                Thread.Sleep(100);
                if (View(out mlist) && mlist.Count(tem => tem.Type == 3 && tem.Flag == 0) > 0) {
                    break;
                }
            }
            int finishCounter = 0;
            WorkStateShow(GameState.副本中);
            //出错位置定位
            dm.DmKeyPress("f", 5);
            while (!CoreClosingControler && Controler.PGControler) {
                //退出副本的条件
                if (!string.IsNullOrEmpty(TheGamer.MapName) && TheGamer.MapName != "圣兽山副本") {
                    break;
                }
                Thread.Sleep(100);
                //如果环境的遍历失败了就重新遍历一次
                if (!View(out mlist)) continue;
                //对地面包裹进行处理
                if (!Controler.JWControler && mlist.Count(tem => tem.IsBag) > 0) {
                    //捡物处理
                    //SzLog(string.Format("Catch0\r\n"));
                    Drop();
                    foreach (var tem in mlist.Where(tem => tem.IsBag).OrderBy(tem => tem.HowFar)) {
                        Catch(tem.ID);
                        var sleepTime = (int)(300 * (3 + tem.HowFar));
                        sleepTime = (sleepTime < 5000) ? sleepTime : 5000;
                        Thread.Sleep(sleepTime);
                    }
                    //SzLog(string.Format("Catch1\r\n"));
                }


                //按照副本的状态进行判断
                if (!hasFinish) {
                    #region 坐骑状态检查
                    if (TheGamer.Horse) {
                        //SzLog(string.Format("Horse0\r\n"));
                        dm.DmKeyPress("f", 5);
                        Thread.Sleep(1000);
                        HorseOperate(false);
                        Thread.Sleep(500);
                        //SzLog(string.Format("Horse1\r\n"));
                    }
                    #endregion

                    //统计一下野猪头目的存在
                    if (mlist.Count(tem => tem.Type == 3 && tem.Flag >= 0 && tem.HP <= 0 && tem.Name == "野猪头目") > 0) {
                        hasFinish = true;
                        finishCounter = 0;
                        //SzLog(string.Format("ExitFB\r\n"));
                    }
                    //坐标
                    if (TheGamer.JsXY.HowFar(88, 63) > 4 && TheGamer.JsStaticCounter > 30) {
                        //SzLog(string.Format("WalkBack0\r\n"));
                        WalkToXy(88, 63);
                        Thread.Sleep(100);
                        //SzLog(string.Format("WalkBack1\r\n"));
                    }
                }
                else {
                    HorseOperate(true);
                    Thread.Sleep(500);
                    if (AutoGetOutOfShengShouShanFb.Value && TheGamer.JsStaticCounter > 100 && mlist.Count(tem => tem.IsBag) < 1 && finishCounter++ > 20) {

                        WalkToXy(237, 233);
                        Thread.Sleep(2000);
                        ConfirmBtnDeal();
                    }
                }
            }
            Controler.FKControler = false;
            WorkStateShow(GameState.野猪);
        }

        /// <summary>
        /// 返回大理
        /// </summary>
        private void ReturnDaLi() {
            WorkStateShow(GameState.回城);
            dm.DmKeyPress("F", 5);
            HorseOperate(false);
            Thread.Sleep(2000);
            Skill_JS(0x16);//返回大理的传送调
        }

        /// <summary>
        /// 搜索副本
        /// </summary>
        /// <param name="searchLu"></param>
        /// <param name="luId"></param>
        private void SearchAndWaitforGetInFb(List<XY> searchLu, ref int luId) {
            if (TheGamer.MapChangeCounter < 30)
                return;
            bool leader = false;
            //队长循环检查而队员根据等待时间检查
            bool findNpc = false;
            if (FbTeamCheck(ref leader, true) && leader) {
                if (!FbTeamCheck(ref leader, false))
                    return;
                WorkStateShow(GameState.搜索);
                //检查是否是队长
                const string npcMonsters = "年兽|龙龟|黄鸟|麒麟|英招";
                //Console.WriteLine("队长组队跟随");
                while (!CoreClosingControler && Controler.PGControler) {
                    if ((FbTeamCheck(ref leader, true) && !leader) ||
                        (!string.IsNullOrEmpty(TheGamer.MapName) && TheGamer.MapName != "圣兽山"))
                        break;
                    Thread.Sleep(100);
                    List<Monster> mlist;
                    if (View(out mlist)) {
                        var ev = mlist.Where(tem => tem.Flag == 0 && !string.IsNullOrEmpty(tem.Name) && tem.Type == 3 && npcMonsters.Contains(tem.Name)).OrderBy(tem => tem.HowFar);
                        foreach (var tem in ev) {
                            WalkToXy(tem.MonXy);
                            Thread.Sleep(1000);
                            if (TalkNpc(tem.ID, "拯救灵兽")) {
                                Thread.Sleep(5000);
                            }
                            Thread.Sleep(500);
                            findNpc = true;
                            break;
                        }
                    }
                    //如果当前找到了NPC那么就继续遍历 否则进行坐标相关处理
                    if (findNpc) {
                        findNpc = false;
                        continue;
                    }
                    if (TheGamer.JsXY.HowFar(searchLu[luId]) < 4) {
                        luId = (++luId) % searchLu.Count;
                        if (luId == 0) {
                            _nonePig = true;
                            return;
                        }
                        Walk(searchLu[luId]);
                        Thread.Sleep(200);
                    }
                    if (TheGamer.JsStaticCounter > 20) {
                        Walk(searchLu[luId]);
                        Thread.Sleep(200);
                    }
                }
                WorkStateShow(GameState.野猪);
            }
            else {
                if (TheGamer.MapChangeCounter > 50 && TheGamer.JsStaticCounter > 100) {
                    FbTeamCheck(ref leader, false);
                }
                //非队长模式对路标监控以方便进行信息对比识别
                if (TheGamer.JsXY.HowFar(searchLu[luId]) < 10) {
                    luId = (++luId) % searchLu.Count;
                    if (luId == 0) {
                        _nonePig = true;
                        return;
                    }
                }
                Thread.Sleep(100);
            }
        }

        /// <summary>
        /// 通过各种途径去圣兽山
        /// </summary>
        private void GotoShengshouShan() {
            //在山上的
            if (TheGamer.MapName == "圣兽山")
                return;
            if (TheGamer.MapName == "玄武岛") {
                WalkToXy(290, 60);
                for (int i = 0; i < 20; i++) {
                    if (ConfirmBtnDeal()) {
                        Thread.Sleep(5000);
                        break;
                    }
                    Thread.Sleep(500);
                }
            }
            else if (TheGamer.MapName == "洛阳") {
                var yunHaner = new Monster();
                if (TheGamer.JsXY.HowFar(275, 293) > 2) {
                    WalkToXy(275, 293);
                }
                else if (GetNpc("云涵儿", ref yunHaner) && TalkNpc(yunHaner.ID, "QSSS_090302_1")) {
                    Thread.Sleep(500);
                    for (int i = 0; i < 20; i++) {
                        if (ConfirmBtnDeal()) {
                            Thread.Sleep(5000);
                            break;
                        }
                        Thread.Sleep(500);
                    }
                }
            }
            else {
                //到洛阳NPC的位置
                Walk("洛阳", true, 275, 293);
            }
        }
        #endregion

        #region 收元宝
        /// <summary>
        /// 收元宝主线程
        /// </summary>
        private void ShouYbThread() {
            Controler.ShouYuanBaoConroler = true;
            DateTime lsCheckTime = DateTime.Now;
            var lsHanHuaTime = DateTime.Now.AddDays(-1);
            var lsHanHuaTimeShiJi = DateTime.Now.AddDays(-1);
            WorkStateShow(GameState.收元宝);
            while (!CoreClosingControler && Controler.ShouYuanBaoConroler) {
                if ((DateTime.Now - lsHanHuaTime).TotalSeconds > 20) {
                    string str;
                    if ((DateTime.Now - lsHanHuaTimeShiJi).TotalMinutes > 3) {
                        int nowRestMoney = NativeMethods.Ri(dwProcessId, Data.JS, Data.JS_OFF_1, Data.JS_OFF_2, Data.JS_OFF_3, Data.JS_MONEY) / 10000;
                        str = string.Format(@"/W {3}金收1000YB，#56按比例收元宝，#56卖的到{0}({1},{2})处与{4}直接交易#56还有{5}金",
                            TheGamer.MapName, (int)TheGamer.JsXY.X, (int)TheGamer.JsXY.Y, (int)(FrmMain.YuanBaoBiLi.Value * 1000), TheGamer.Name, nowRestMoney);
                        lsHanHuaTimeShiJi = DateTime.Now;
                    }
                    else {
                        str = string.Format(@"{0}金收1000YB，按比例收元宝，卖的直接点我交易!!", (int)(FrmMain.YuanBaoBiLi.Value * 1000));
                        lsHanHuaTime = DateTime.Now;
                    }
                    Bunking(str);
                }
                Thread.Sleep(1000);
                if ((DateTime.Now - lsCheckTime).TotalSeconds > 3) {
                    dm.DmKeyPress("j");
                    Thread.Sleep(1000);
                }
                CheckJiaoYiMianBan();
            }
            WorkStateShow(GameState.空闲);

        }

        #region 收元宝的DM数据集合
        const string shangWeiSuoding = "尚未锁定";
        const string yiJingSuoding = "已经锁定";
        const string noColor = "bbbbbb-000000";//表示按钮为不可用状态
        private const string yuanBaoPiaoDingWei = "元宝定位";
        private const string yuanBaoPiaoDingweiColor = "ffffff-000000";//元宝票定位颜色
        private const string yuanBaoPiaoValueColor = "07c702-0fffff";
        #endregion

        /// <summary>
        /// 搜索交易面板
        /// </summary>
        /// <returns></returns>
        public void CheckJiaoYiMianBan() {
            int x, y;
            //检查未锁定的标记
            if (dm.DmRcWord(shangWeiSuoding, noColor, out x, out y)) {
                HuanYuanBaoLogMsg(@"检查到交易面板,开始本次交易……");
                //HuanYuanBaoLogMsg(string.Format(@"定位交易面板成功：{0}，{1}", x, y));
                for (int i = 0; i < 20; i++) {
                    if (!dm.DmRcWord(shangWeiSuoding, noColor, out x, out y))
                        break;
                    int value;
                    if (CheckYbPiao(out value, x, y)) {
                        ShuRuJinBi(x, y, value);
                    }
                    Thread.Sleep(1000);
                }
            }
        }

        /// <summary>
        /// 元宝日志锁
        /// 用于保证io正常
        /// </summary>
        private static readonly object ShouYuanLock = new object();

        /// <summary>
        ///  收元宝日志
        /// </summary>
        /// <param name="str"></param>
        private void HuanYuanBaoLogMsg(string str) {
            MuYue.Log.LogService.Write("[{0}]{1}", PermaName, str);
        }

        /// <summary>
        /// 交易执行过程
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="value"></param>
        private void ShuRuJinBi(int x, int y, int value) {
            int nowRestMoney = NativeMethods.Ri(dwProcessId, Data.JS, Data.JS_OFF_1, Data.JS_OFF_2, Data.JS_OFF_3, Data.JS_MONEY) / 10000;

            if (nowRestMoney < value) {
                HuanYuanBaoLogMsg(@"当前的金币余额不足了额！取消本次交易");
                dm.DmKeyPress("esc");
                return;
            }
            dm.DmClick(x + 220, y - 310);
            //输入金币
            Thread.Sleep(500);
            dm.SendString(gameHwnd, value.ToString(CultureInfo.InvariantCulture));
            //检查金币
            Thread.Sleep(200);
            ConfirmBtnDeal();

            dm.DmClick(x + 190, y + 7);
            Thread.Sleep(200);
            //dm.DmClick(50, 50, 0);
            //等待交易锁定
            DateTime nw = DateTime.Now;
            //30秒等待时间
            int error = 3;
            while ((DateTime.Now - nw).TotalSeconds < 30) {
                int temx, temy;
                if (dm.DmRcWord(yiJingSuoding, noColor, out temx, out temy)) {
                    HuanYuanBaoLogMsg(@"检测到对方已经锁定了本次交易,进入元宝确认阶段……");
                    //HuanYuanBaoLogMsg(string.Format(@"对方锁定了:{0},{1}", temx, temy));
                    int nwValue;
                    if (CheckYbPiao(out nwValue, x, y) && nwValue == value) {
                        const string path = "./元宝记录/图片记录";
                        if (!Directory.Exists(path)) {
                            Directory.CreateDirectory(path);
                        }
                        // ReSharper disable once SpecifyACultureInStringConversionExplicitly
                        var fileName = string.Format("{0}/{1}.png", path, DateTime.Now.ToString("s").Replace("/", "").Replace(" ", "-").Replace(":", ""));
                        HuanYuanBaoLogMsg(@"元宝价值确认,截图保留本次交易!");
                        dm.CapturePng(0, 0, 2000, 2000, fileName);
                        HuanYuanBaoLogMsg(string.Format("截图名为：{0}", fileName));
                        dm.DmClick(x + 155, y + 38);
                        for (int i = 0; i < 15; i++) {
                            Thread.Sleep(1000);
                            if (!dm.DmRcWord(yiJingSuoding, noColor, out x, out y)) {
                                HuanYuanBaoLogMsg(@"交易面板已经关闭了!");
                                //本次交易结束
                                break;
                            }
                        }
                    }
                    break;
                }
                if (!dm.DmRcWord(shangWeiSuoding, noColor, out x, out y)) {
                    HuanYuanBaoLogMsg(@"检测到交易已经取消了!");
                    if (--error < 0)
                        break;
                }
                Thread.Sleep(1000);
            }
            List<GamerBag> baglist;
            ViewMyBag(out baglist);
            var ybList = baglist.Where(tem => tem.Name == "元宝票").Select(i => i.ID).ToList();
            UseBag(ybList);
            HuanYuanBaoLogMsg(@"本次交易结束");
            dm.DmKeyPress("esc");
            HuanYuanBaoLogMsg(@"\r\n\r\n\r\n");
        }


        /// <summary>
        /// 元宝票检查
        /// </summary>
        /// <param name="ybValue"></param>
        /// <param name="mx"></param>
        /// <param name="my"></param>
        /// <returns></returns>
        private bool CheckYbPiao(out int ybValue, int mx, int my) {
            //HuanYuanBaoLogMsg(@"查询是否存在元宝票");
            ybValue = 0;
            dm.DmClick(50, 50, 0);
            Thread.Sleep(100);
            dm.DmClick(mx - 60, my - 255, 0);
            Thread.Sleep(200);
            if (dm.DmRcWord(yuanBaoPiaoDingWei, yuanBaoPiaoDingweiColor, out mx, out my)) {
                HuanYuanBaoLogMsg(@"对方已经放上了元宝票,进行价值检测……");
                //HuanYuanBaoLogMsg(string.Format(@"元宝定位成功：{0}，{1}", mx, my));
                string value = dm.Ocr(mx + 100, my, mx + 130, my + 15, yuanBaoPiaoValueColor, 1);
                HuanYuanBaoLogMsg(string.Format(@"元宝价值为：{0}", value));
                if (int.TryParse(value, out ybValue)) {
                    ybValue = (int)(FrmMain.YuanBaoBiLi.Value * ybValue);
                    HuanYuanBaoLogMsg(string.Format(@"本次应该支付的金币为：{0}", ybValue));
                    return true;
                }
                HuanYuanBaoLogMsg(@"元宝票价格识别失败了");
            }
            HuanYuanBaoLogMsg(@"没有找到元宝票");
            return false;
        }
        #endregion

        #region  种植模块

        /// <summary>
        /// 种植配置对象
        /// </summary>
        public ZhongZhiInfo TheZhongZhiInfo;

        /// <summary>
        /// 将种植内存配置进行存档
        /// </summary>
        public void SaveZhongZhiConfig() {
            TheZhongZhiInfo.Save(PermaName);
        }

        /// <summary>
        /// 种植函数线程
        /// </summary>
        public void ZhongZhiThread() {

            Controler.ZZControler = true;
            WorkStateShow(GameState.种植);

            //是否等待成熟
            bool isWaitingForOk = ZhongZhiStartInfoCheck();
            int waitSeconds = GetZhongZhiWaitingTime();
            if (isWaitingForOk) {
                SendMessageToUi(string.Format("成熟时间：{0}", TheZhongZhiInfo.LastZhongXiaTime.AddSeconds(waitSeconds)));
            }

            string map = TheZhongZhiInfo.DefaultZhongZhiMap;
            var lu = new List<XY>();
            var luId = 0;

            if (!ZuoBiao("./system/" + map + ".zz", ref lu)) {
                SendMessageToUi("无法正确的加载到种植地图的寻路坐标！");
                Controler.ZZControler = false;
            }

            while (!CoreClosingControler && Controler.ZZControler) {
                Thread.Sleep(100);
                if (isWaitingForOk) {
                    if ((DateTime.Now - TheZhongZhiInfo.LastZhongXiaTime).TotalSeconds > waitSeconds) {
                        //等待和执行收割种植过程
                        isWaitingForOk = ReapAndPlant();
                        if (isWaitingForOk) {
                            waitSeconds = GetZhongZhiWaitingTime();
                        }
                    }
                }
                else if (TheGamer.MapName != TheZhongZhiInfo.DefaultZhongZhiMap) {
                    if (map != TheZhongZhiInfo.DefaultZhongZhiMap) {
                        luId = 0;
                        map = TheZhongZhiInfo.DefaultZhongZhiMap;
                        if (!ZuoBiao("./system/" + map + ".zz", ref lu)) {
                            SendMessageToUi("无法正确的加载到种植地图的寻路坐标！");
                            Controler.ZZControler = false;
                            break;
                        }
                    }
                    //当前地图不等于种植地图
                    Walk(map);
                    Thread.Sleep(1000);
                }
                else {
                    //检查是否存在空地
                    if (CheckEmptyLand()) {
                        isWaitingForOk = Plant();
                        if (isWaitingForOk) {
                            waitSeconds = GetZhongZhiWaitingTime();
                        }
                    }
                    else {
                        //注意坐标初始化
                        if (lu[luId].HowFar(TheGamer.JsXY) < 4) {
                            luId++;
                            luId = luId % lu.Count;
                            Walk(lu[luId]);
                        }
                        else if (TheGamer.MapChangeCounter > 50 && TheGamer.JsStaticCounter > 10) {
                            Walk(lu[luId]);
                        }
                    }
                }
            }
            WorkStateShow(GameState.空闲);
        }

        /// <summary>
        /// 本地日志消息调用函数
        /// </summary>
        /// <param name="strMsg"></param>
        private void SendMessageToUi(string strMsg, params object[] obj) {
            if (obj != null && obj.Length > 0) {
                strMsg = string.Format(strMsg, obj);
            }
            MsgListener.CommonMsgShow(PermaName, strMsg);
        }

        /// <summary>
        /// 种植精力过剩处理程序
        /// </summary>
        private void ContinueCaiJi() {
            if (TheZhongZhiInfo.LastZhongZhiShuZhi == ZhongZhiShuZhi.早产) {
                if (dm.GetWindowState(3) == 0 && !TheGamer.Dati) {
                    dm.SetWindowState(2);
                    Thread.Sleep(200);
                }
                return;
            }
            if (!Conf.ZhongzhiContinueCaiji.Value)
                return;
            if (TheGamer.Energy > TheGamer.EnergyMax * 0.7) {
                //将最小化窗口打开
                if (dm.GetWindowState(3) == 1) {
                    dm.SetWindowState(12);
                    Thread.Sleep(200);
                }
                //SendMessageToUi("[种植附加]:执行采集");
                CaiJiMainThread();
                //SendMessageToUi("[种植附加]:退出采集,继续执行种植");
                WorkStateShow(GameState.种植);
            }
            else {

                //执行打坐或者去卖掉东西
                List<GamerBag> bags;
                ViewMyBag(out bags, 0, 60);
                var i = 0;
                if (Conf.CaiJiBaitan.Value)
                    foreach (var b in bags) {
                        foreach (var n in BaitanConf.PriceMap) {
                            if (b.Name == n.Key) {
                                i++;
                                break;
                            }
                        }
                    }
                if (i > 5)
                    Baitan();
                else {
                    HorseOperate(false);
                    Thread.Sleep(2000);
                    Skill_JS(0x23);
                }
            }
            //窗口最小化
            if (dm.GetWindowState(3) == 0 && !TheGamer.Dati) {
                dm.SetWindowState(2);
                Thread.Sleep(200);
            }
        }

        /// <summary>
        /// 收获并且连续种植
        /// </summary>
        /// <returns></returns>
        private bool ReapAndPlant() {

            //执行收摊操作

            if (TheGamer.State == 10) {
                ShouTan();
            }

            string openDialog, nextPlantName;
            var lastPlantName = GetPlantInfo(out openDialog, out nextPlantName);
            var error = 0;
            Monster plant = null;//作物标记
            Monster daoCaoRen = null;
            while (!CoreClosingControler && Controler.ZZControler) {

                //发现错误后退出循环
                if (error > 40) {
                    SendMessageToUi("收割部分出现错误。");
                    return false;
                }

                Thread.Sleep(200);
                //返回种植地图
                if (TheGamer.MapName != TheZhongZhiInfo.LastZhongZhiMap) {
                    Walk(TheZhongZhiInfo.LastZhongZhiMap);
                    Thread.Sleep(2000);
                    continue;
                }
                //返回种植坐标
                if (TheGamer.JsXY.HowFar(TheZhongZhiInfo.LastZhongZhiXY) > 5) {
                    WalkToXy(TheZhongZhiInfo.LastZhongZhiXY);
                    Thread.Sleep(2000);
                    continue;
                }

                //下马操作
                if (TheGamer.Horse) {
                    HorseOperate(false);
                }

                List<Monster> mlist;
                //稻草人
                if (!View(out mlist))
                    continue;

                try {
                    if (daoCaoRen == null) {
                        //SendMessageToUi("定位稻草人");

                        daoCaoRen = mlist.FirstOrDefault(t =>
                            t.Type == 3 &&
                            t.Flag > -1 &&
                            t.MonXy.HowFar(TheZhongZhiInfo.LastZhongZhiXY) < 5f);

                        if (daoCaoRen == null || string.IsNullOrWhiteSpace(daoCaoRen.Name)) {
                            daoCaoRen = null;
                            error++;
                            Thread.Sleep(1000);
                            continue;
                        }
                    }

                    //定位需要收获的作物
                    if (plant == null) {
                        //SendMessageToUi("定标作物检索");
                        plant = mlist.FirstOrDefault(t =>
                            t.Type == 8 &&
                            t.Name == lastPlantName &&
                            t.MonXy.HowFar(daoCaoRen.MonXy) < 5f
                           );

                        if (plant == null || string.IsNullOrWhiteSpace(plant.Name)) {
                            error++;
                            plant = null;
                            Thread.Sleep(1000);
                            continue;
                        }
                    }

                    //查询作物
                    var plants = mlist.Where(
                        t => Math.Abs(t.ID - plant.ID) < 4 &&
                        t.MonXy.HowFar(daoCaoRen.MonXy) < 5f &&
                        t.Type != 3).ToArray();

                    //作物数目校准
                    if (plants.Length == 0) {
                        error++;
                    }

                    //收割作物
                    for (int i = 0; i < plants.Length - 1; i++) {
                        HavingHarvest(plants[i]);
                        Thread.Sleep(500);
                    }

                    //打开稻草人对话信息
                    WalkToXy(daoCaoRen.MonXy);
                    if (TalkNpc(daoCaoRen.ID, openDialog)) {
                        Thread.Sleep(1000);
                        for (int j = 0; j < 30; j++) {
                            Thread.Sleep(300);
                            if (NpcDiaCheck(ref nextPlantName)) {
                                break;
                            }
                        }
                    }
                    //如果还有一个作物没有收割就执行收割
                    if (plants.Length > 0) {
                        HavingHarvest(plants[plants.Length - 1]);
                    }

                    //执行种植
                    if (PlantImediately(nextPlantName, daoCaoRen)) {
                        return true;
                    }

                }
                catch (Exception ex) {
                    SendMessageToUi("错误捕获");
                    SendMessageToUi(ex.Message);
                    SendMessageToUi(ex.StackTrace);
                }
                error++;
            }
            return false;
        }

        /// <summary>
        /// 直接收割起来
        /// </summary>
        /// <param name="monster"></param>
        private void HavingHarvest(Monster monster) {
            //SendMessageToUi(string.Format("收割({0})[{1},{2}]", monster.Name, monster.MonXy.X, monster.MonXy.Y));
            Thread.Sleep(500);
            Walk(monster.MonXy);
            Thread.Sleep(2000);
            Catch(monster.ID);
            for (int i = 0; i < 200; i++) {
                Thread.Sleep(50);
                if (NativeMethods.Ri(dwProcessId, Data.FLAG_BAG_FLOOR, Data.FLAG_OFF_1, Data.FLAG_OFF_2, Data.FLAG_OFF_3) == 1) {
                    //收割成功了
                    Catch();
                    return;
                }
            }
        }

        /// <summary>
        /// 实际种植执行过程
        /// </summary>
        /// <returns></returns>
        private bool Plant() {
            List<Monster> mlist;
            //如果环境遍历失败
            if (!View(out mlist))
                return false;
            //执行作物检索
            string openDialog, plantName;

            GetPlantInfo(out openDialog, out plantName);

            //稻草人遍历
            var daoChaoRens = mlist.Where(tem => tem.Flag > -1 && tem.Type == 3 && tem.Name == "稻草人").OrderBy(tem => tem.HowFar);
            //找到NPC执行种植
            foreach (var daoChaoRen in daoChaoRens) {
                //走到身边去
                WalkToXy(daoChaoRen.MonXy);
                if (TalkNpc(daoChaoRen.ID, openDialog)) {
                    for (int i = 0; i < 50; i++) {
                        Thread.Sleep(100);
                        if (PlantImediately(plantName, daoChaoRen)) {
                            return true;
                        }
                    }
                }
                break;
            }
            return false;
        }

        /// <summary>
        /// 获取作物种植时候的信息
        /// </summary>
        /// <param name="openDialog"></param>
        /// <param name="plantName"></param>
        private string GetPlantInfo(out string openDialog, out string plantName) {
            var lastName = TheZhongZhiInfo.LastZhongZhiShuZhi + TheZhongZhiInfo.LastZhongZhiZuoWu;
            //早产转换种植检查
            if (TheZhongZhiInfo.DefaultZhongZhiShuZhi == ZhongZhiShuZhi.早产 && TheZhongZhiInfo.AutoChangetZaoToWan && TheGamer.Energy - 30 < TheZhongZhiInfo.LowestEnergy) {
                TheZhongZhiInfo.LastZhongZhiShuZhi = ZhongZhiShuZhi.晚产;
            }
            else {
                TheZhongZhiInfo.LastZhongZhiShuZhi = TheZhongZhiInfo.DefaultZhongZhiShuZhi;
            }
            openDialog = (TheZhongZhiInfo.LastZhongZhiShuZhi == ZhongZhiShuZhi.早产) ? "种植早产植物" : "种植晚产植物";
            TheZhongZhiInfo.LastZhongZhiZuoWu = TheZhongZhiInfo.DefaultZhongZhiZuoWu;
            plantName = TheZhongZhiInfo.LastZhongZhiShuZhi + TheZhongZhiInfo.LastZhongZhiZuoWu;
            return lastName;
        }

        /// <summary>
        ///  直接执行种植
        /// </summary>
        /// <param name="plantName"></param>
        /// <returns></returns>
        private bool PlantImediately(string plantName, Monster daoCaoRen) {
            if (TalkNpc(plantName)) {
                var shouldia1 = "你已经开始种植";
                var shouldia2 = "不能连续种植";
                var succeed = false;
                for (int i = 0; i < 50; i++) {
                    Thread.Sleep(100);
                    if (NpcDiaCheck(ref shouldia1)) {
                        TheZhongZhiInfo.LastZhongXiaTime = DateTime.Now;
                        succeed = true;
                    }
                    else if (NpcDiaCheck(ref shouldia2)) {
                        int start = shouldia2.IndexOf("大约", StringComparison.Ordinal);
                        var stop = shouldia2.IndexOf("分钟后", StringComparison.Ordinal);
                        int minute;
                        //不能连续种植，大约4分钟后可以再次种植。8
                        start += "大约".Length;
                        var timestring = shouldia2.Substring(start, stop - start);
                        if (int.TryParse(timestring, out minute)) {
                            //增加1分钟
                            minute++;
                            //转化为妙
                            var sencond = minute * 60;
                            sencond = GetZhongZhiWaitingTime() - sencond;
                            //通过计算计算出种植中下的时间
                            TheZhongZhiInfo.LastZhongXiaTime = DateTime.Now.AddSeconds(-1 * sencond);
                            succeed = true;
                        }
                    }
                    if (succeed) {
                        //记录下种植时间 地点 和实际执行的种植作物
                        TheZhongZhiInfo.LastZhongZhiMap = TheGamer.MapName;
                        TheZhongZhiInfo.LastZhongZhiXY = daoCaoRen.MonXy;
                        SaveZhongZhiConfig();
                        SendMessageToUi("成熟时间：{0}", TheZhongZhiInfo.LastZhongXiaTime.AddSeconds(GetZhongZhiWaitingTime()));
                        ContinueCaiJi();
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 检查当前位置是否是空地
        /// </summary>
        /// <returns></returns>
        private bool CheckEmptyLand() {
            List<Monster> mlist;
            if (!View(out mlist))
                return false;
            var en = mlist.Where(tem => tem.Type == 3 && tem.Flag > -1 && tem.Name == "稻草人" && mlist.Count(temMon => temMon.Type == 8 && temMon.MonXy.HowFar(tem.MonXy) < 5) == 0);
            foreach (var monster in en) {
                WalkToXy(monster.MonXy);
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获取种植应该等待是秒
        /// </summary>
        /// <returns></returns>
        private int GetZhongZhiWaitingTime() {
            return 2 + ((TheZhongZhiInfo.LastZhongZhiShuZhi == ZhongZhiShuZhi.早产) ? 5 : 70) * 60;
        }

        /// <summary>
        /// 种植启动时状态检查
        /// </summary>
        /// <returns></returns>
        private bool ZhongZhiStartInfoCheck() {
            var waitSeconds = GetZhongZhiWaitingTime();
            if ((DateTime.Now - TheZhongZhiInfo.LastZhongXiaTime).TotalSeconds < waitSeconds) {
                //种植记录是正确的 执行等待任务
                return true;
            }
            //执行一下种植
            return Plant();
        }
        #endregion

        #region 自动喊话

        private class BunkingElement
        {
            internal DirectDealGame TheOne { private set; get; }
            internal DateTime LsDateTime { set; get; }
            public BunkingElement(DirectDealGame theShower, DateTime dateTime) {
                TheOne = theShower;
                LsDateTime = dateTime;
            }
        }


        private static readonly List<BunkingElement> BunkingList = new List<BunkingElement>();

        /// <summary>
        /// 喊话任务
        /// </summary>
        private static Task _bunkingTask;
        /// <summary>
        /// 喊话内容
        /// </summary>
        /// <param name="theShower"></param>
        internal static void BunkingAdd(DirectDealGame theShower) {
            BunkingList.Add(new BunkingElement(theShower, DateTime.Now.AddMinutes(-10)));
            theShower.Controler.BunkingControler = true;
            if (_bunkingTask == null || _bunkingTask.Status != TaskStatus.Running) {
                _bunkingTask = new Task(BunkingThread);
                _bunkingTask.Start();
            }
        }

        private static void BunkingThread() {
            MsgListener.CommonMsgShow("喊话系统", "线程启动");
            while (BunkingList.Count > 0) {
                Thread.Sleep(300);
                for (int i = 0; i < BunkingList.Count; i++) {
                    var theOne = BunkingList[i].TheOne;
                    //检查喊话状态
                    if (theOne.CoreClosingControler || !BunkingList[i].TheOne.Controler.BunkingControler) {
                        BunkingList.RemoveAt(i);
                        MsgListener.CommonMsgShow(theOne.PermaName, "喊话退出");
                        break;
                    }
                    if ((DateTime.Now - BunkingList[i].LsDateTime).TotalMinutes > 3.1) {
                        theOne.Bunking(string.Format("/W {0}", theOne.Conf.BunkingConfig.Value));
                        BunkingList[i].LsDateTime = DateTime.Now;
                    }
                }
            }
            MsgListener.CommonMsgShow("喊话系统", "线程退出");
        }

        private void Bunking(string strMsg) {
            this.dm.DmKeyPress("enter");
            this.dm.SendString(gameHwnd, strMsg);
            this.dm.DmKeyPress("enter");
        }

        #endregion

        #region 自动打图

        public void AutoDatu() {
            string map = "";
            XY xy = new XY();
            Controler.DatuController = true;
            WorkStateShow(GameState.打图);
            int error = 0;
            while (!CoreClosingControler && Controler.DatuController) {
                Thread.Sleep(300);
                if (AcceptDatuTask(ref error)) {
                    if (!string.IsNullOrEmpty(map) || GetMapInfoFromChengelin(out map, out xy)) {
                        Walk(map, true, xy.X, xy.Y);
                        //到达目的地之后
                        if (TheGamer.MapName == map && TheGamer.JsXY.HowFar(xy) < 2) {
                            //下马并且建立监视
                            HorseOperate(false);
                            Thread.Sleep(3000);
                            //建立比对表    
                            DatuKillAndFinish();
                        }
                    }
                }
                else if (!string.IsNullOrEmpty(map)) {
                    map = "";
                    error = 0;
                }
                else if (error > 10) {
                    Controler.DatuController = false;
                }
            }
            WorkStateShow(GameState.空闲);
        }
        //完成
        private void DatuKillAndFinish() {
            List<Monster> origin;
            if (View(out origin)) {
                List<Monster> mList;
                int error = 0;
                UseChengelin(true);
                while (!CoreClosingControler && Controler.DatuController) {
                    Thread.Sleep(200);
                    Drop();
                    if (TheGamer.JsStaticCounter > 30 && View(out mList)) {
                        //查找怪物
                        var monsters = mList.Where(t => t.HP > 0 && t.HowFar < 10 && origin.Count(ot => ot.ID == t.ID || ot.Name == t.Name) == 0 && t.Type == 3 && t.Flag > 15).ToList();
                        if (monsters.Count > 0) {
                            foreach (var monster in monsters) {
                                KillMonster(monster);
                            }
                        }
                        else if (mList.Count(t => t.IsBag) > 0) {
                            foreach (var mon in mList) {
                                if (mon.IsBag) {
                                    error = 100;
                                    Catch(mon.ID);
                                    Thread.Sleep(2000);
                                }
                            }
                        }
                        else if (error++ > 100) {
                            UseDingweifu();
                            //检查定位符
                            break;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 使用定位符
        /// </summary>
        private void UseDingweifu() {
            List<GamerBag> baglist;
            ViewMyBag(out baglist, 0, 30);
            var idList = new List<int>();
            foreach (var bag in baglist) {
                if (bag.Name.Contains("色定位符")) {
                    idList.Add(bag.ID);
                }
            }
            if (idList.Count > 0) {
                Skill_JS(0xf8);
                Thread.Sleep(500);
                UseBag(idList);
                Thread.Sleep(2000);
            }
        }

        /// <summary>
        /// 使用惩恶令
        /// </summary>
        /// <param name="use"></param>
        /// <returns></returns>
        private bool UseChengelin(bool use) {
            return UseBag("惩恶令", use, start: 60);
            //List<GamerBag> baglist;
            //ViewMyBag(out baglist, 60);
            //var idList = new List<int>();
            //foreach (var bag in baglist)
            //{
            //    if (bag.Name == "惩恶令")
            //    {
            //        idList.Add(bag.ID);
            //        if (!use)
            //            return true;
            //    }
            //}
            //if (use && idList.Count > 0)
            //{
            //    UseBag(idList);
            //    return true;
            //}
            //return false;
        }

        /// <summary>
        /// 到苏州接收打图任务
        /// </summary>
        /// <returns></returns>
        private bool AcceptDatuTask(ref int error) {
            if (UseChengelin(false)) {
                return true;
            }
            if (TheGamer.JsStaticCounter > 20) {
                //返回苏州
                if (TheGamer.MapName != "苏州") {
                    Walk("苏州");
                    Thread.Sleep(2000);
                    return false;
                }
                //走到坐标
                var npcXy = new XY(224, 226);
                if (TheGamer.JsXY.HowFar(npcXy) > 2) {
                    WalkToXy(npcXy);
                    Thread.Sleep(500);
                    return false;
                }
                Monster npc = new Monster();
                if (GetNpc("吴玠", ref npc)) {
                    TalkNpc(npc.ID, "CXDT_090304_01");
                    Thread.Sleep(2000);
                    //检查是否存在惩恶令
                    if (UseChengelin(false)) {
                        return true;
                    }
                    error++;
                    var messionState = MessionState.未知;
                    AcceptOrFinish(ref messionState);
                    Console.WriteLine(messionState);
                }
            }
            Thread.Sleep(2000);
            return false;
        }


        private bool GetMapInfoFromChengelin(out string map, out XY theXy) {
            //关闭所有的东西
            dm.DmKeyPress("esc");
            map = "";
            theXy = new XY();
            if (!UseChengelin(true)) {
                return false;
            }
            Thread.Sleep(2000);//#{DTYH_121009_18**敦煌*110*170*8}
            var taskMsg = "DTYH_121009_18";
            if (NpcDiaCheck(ref taskMsg)) {
                taskMsg = StringToLegal(taskMsg);
                if (taskMsg.Contains("DTYH_121009_18")) {
                    string[] taskMsgPices = taskMsg.Split(new[] { "*" }, StringSplitOptions.RemoveEmptyEntries);
                    if (taskMsgPices.Length == 5) {
                        map = taskMsgPices[1];
                        if (float.TryParse(taskMsgPices[2], out theXy.X) && float.TryParse(taskMsgPices[3], out theXy.Y)) {
                            return true;
                        }
                    }
                }
            }

            //int btnCount = NativeMethods.Rb(dwProcessId, Data.CALL_NPCDIA, 0x34, 4);
            //for (int i = 0; i < btnCount; i++) {
            //    var taskMsg = NativeMethods.Rs(dwProcessId, Data.CALL_NPCDIA, 0x34, (8 + (i * 0x118)) + 0xe);
            //    taskMsg = StringToLegal(taskMsg);
            //    //Common.MsgListener.CommonMsgShow(this.PermaName, taskMsg);
            //    if (taskMsg.Contains("DTYH_121009_18")) {
            //        string[] taskMsgPices = taskMsg.Split(new[] { "*" }, StringSplitOptions.RemoveEmptyEntries);
            //        if (taskMsgPices.Length == 5) {
            //            map = taskMsgPices[1];
            //            if (float.TryParse(taskMsgPices[2], out theXy.X) && float.TryParse(taskMsgPices[3], out theXy.Y)) {
            //                return true;
            //            }
            //        }
            //    }
            //}
            return false;
        }

        #endregion

        #region 自动开图
        /// <summary>
        /// 开图
        /// </summary>
        private void Kt() {
            string map = "";
            XY location = new XY();
            bool working = false;
            Controler.KtController = true;
            WorkStateShow(GameState.开图);
            int error = 0;
            while (!CoreClosingControler && Controler.KtController)//自动开图线程开关
            {
                Thread.Sleep(200);
                //检查是否存在藏宝图
                if (!working) {
                    if (TheGamer.JsStaticCounter < 50)
                        continue;
                    working = KtGetLocation(out map, out location);
                }

                if (working) {
                    //自动前往藏宝图的位置
                    //开启藏宝图
                    if (KtWalk(map, location) && KtOpen()) {
                        working = false;
                        error = 0;
                    }
                }
                else {
                    if (++error > 10) {
                        KtAlarm("已经没有图了");
                        Controler.KtController = false;
                    }
                }
            }
            WorkStateShow(GameState.空闲);
        }

        /// <summary>
        /// 使用藏宝图来获取信息
        /// </summary>
        /// <param name="bag"></param>
        /// <param name="map"></param>
        /// <param name="location"></param>
        /// <returns></returns>
        private bool KtGetLocation(out string map, out XY location) {
            //dm.DmKeyPress("esc");
            map = "";
            location = new XY();

            if (!UseBag("藏宝图", start: 0, end: 30)) {
                return false;
            }

            Thread.Sleep(2000);//#{DTYH_121009_18**敦煌*110*170*8}
            var taskMsg = "才能使用";
            if (NpcDiaCheck(ref taskMsg)) {
                taskMsg = StringToLegal(taskMsg);
                if (taskMsg.Contains("才能使用")) {
                    taskMsg = taskMsg.Replace("你到", "").Replace("的{_INFOAIM", ",");
                    string[] taskMsgPices = taskMsg.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    if (taskMsgPices.Length == 5) {
                        map = taskMsgPices[0];
                        if (float.TryParse(taskMsgPices[1], out location.X) && float.TryParse(taskMsgPices[2], out location.Y)) {
                            MsgListener.CommonMsgShow(PermaName, string.Format("[开图提示]：{0}({1},{2})", map, location.X, location.Y));
                            return true;
                        }
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 在目标位置开启藏宝图
        /// 检查是否打开了宝图
        /// 检查是否进入了副本
        /// </summary>
        /// <param name="bag">藏宝图的包信息</param>
        private bool KtOpen() {
            bool hasOpen = false;
            bool Mx = false;
            bool empty = false;
            while (!CoreClosingControler && Controler.KtController)//使用开图线程开关
            {
                Thread.Sleep(200);
                if (hasOpen) {
                    if (TheGamer.MapName == "墓穴") {
                        if (!Mx) {
                            KtAlarm("进入了墓穴");
                            Thread.Sleep(1000);
                            Mx = true;
                        }
                        continue;
                    }
                    if (TheGamer.JsStaticCounter < 100)
                        continue;
                    break;
                }
                if (HasEmptyBag(0)) {
                    if (!empty) {
                        KtAlarm("物品栏目存在空格了");
                        empty = true;
                    }
                    continue;
                }
                if (UseBag("藏宝图", true, false, start: 0, end: 30)) {
                    Thread.Sleep(3000);
                    //检查使用结果
                    if (!HasEmptyBag(0))
                        continue;
                    hasOpen = true;
                    Thread.Sleep(7000);
                }
                else { break; }
            }
            return true;
        }

        /// <summary>
        /// 前往藏宝图位置
        /// </summary>
        /// <param name="map"></param>
        /// <param name="location"></param>
        /// <returns></returns>
        private bool KtWalk(string map, XY location) {
            while (!CoreClosingControler && Controler.KtController)//使用开图线程开关
            {
                Thread.Sleep(100);
                if (TheGamer.MapName != map) {
                    Walk(map, true, location.X, location.Y);
                }
                else if (location.HowFar(TheGamer.JsXY) > 5) {
                    WalkToXy(location);
                }
                else {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 开图提示信息
        /// </summary>
        private void KtAlarm(string strMsg) {
            Console.Beep();
            MsgListener.CommonMsgShow(PermaName, string.Format("[开图提示]：{0}", strMsg));
            //int musicId = dm.Play(FrmMain.AlarmMusicFile.Value);
            //MsgListener.MsgBoxMsgShow(strMsg, "开图提示");
            //dm.Stop(musicId);
            //音乐提示
        }


        /// <summary>
        /// 使用物品或者检查物品是否存在
        /// </summary>
        /// <param name="use"></param>
        /// <param name="bagName"></param>
        /// <param name="JustOne"></param>
        /// <returns></returns>
        private bool UseBag(string bagName, bool use = true, bool justOne = true, int start = 0, int end = 80, bool isfullName = true) {
            List<GamerBag> baglist;
            ViewMyBag(out baglist, start, end);
            var idList = new List<int>();
            foreach (var bag in baglist) {
                if ((isfullName && bag.Name == bagName) || (!isfullName && bag.Name.Contains(bagName))) {
                    if (!use)
                        return true;
                    idList.Add(bag.ID);
                    if (justOne)
                        break;
                }
            }
            if (use && idList.Count > 0) {
                UseBag(idList);
                return true;
            }
            return false;
        }
        #endregion

        #region 四绝任务系统

        /// <summary>
        /// 四绝线程
        /// </summary>
        private void SiJueZhuangThread() {

            SendMessageToUi("开始四绝任务");
            var start = DateTime.Now;
            Controler.SjController = true;
            WorkStateShow(GameState.四绝);
            SiJueResource.Init();
            while (!CoreClosingControler && Controler.SjController) {
                Thread.Sleep(200);
                if (AreYouThere("苏州")) {
                    DoworksInSuZhou();
                }
                else if (AreYouThere("四绝庄")) {
                    DoworksInSiJueZhuang();
                }
                else {
                    Walk("苏州");
                    Thread.Sleep(1000);
                }
            }
            SendMessageToUi("本次四绝用时:{0:0.00}分", (DateTime.Now - start).TotalMinutes);
            WorkStateShow(GameState.空闲);
        }

        /// <summary>
        /// 四绝庄内处理
        /// </summary>
        /// <param name="workState"></param>
        private void DoworksInSiJueZhuang() {

            #region 程序段思路
            /***********************************************
             * 在这里面要做的事情有哪些
             *  1.打怪
             *      1.在哪儿打 
             *      2.什么时候应该直接打怪
             *      3.什么时候应走位
             *      4.什么时候打什么怪
             *  2.陷阱躲避
             *      1.哪些是陷阱?
             *      2.如果确定出现陷阱的时候走位坐标
             *  要能够识别该做什么最主要的事情就是对环境信息进行分类
             *      1.可以击杀怪物
             *      2.陷阱
             *      3.包裹
             *      4.传送NPC
            *************************************************/
            #endregion

            if (TheGamer.MapChangeCounter < 30)
                return;

            //打怪线程 --- 只负责打怪 至于什么开始打什么时候暂停就由下面的部分进行决定
            CreateFbKillThread(true);
            //初始化状态获取
            var first = SiJueQiaoZhong();
            var now = first ? SiJueResource.FirstHuan : FirstLocationHuan();

            List<Monster> mlist;
            int noMonsterCounter = 0;
            bool noBag = false;
            bool start = false;
            XY shouldStand = GetHuanStartXY(now);
            while (!CoreClosingControler && Controler.SjController) {
                //如果角色已经不再四绝庄了
                if (!string.IsNullOrWhiteSpace(TheGamer.MapName) && !AreYouThere("四绝庄"))
                    break;
                //这里面执行每个环节的具体事务
                Thread.Sleep(100);
                if (!View(out mlist))
                    continue;

                if (!start) {
                    if (mlist.Count(t => t.Type == 3 && t.Flag > 12) > 0) {
                        start = true;
                        HorseOperate(false);
                        continue;
                    }

                    bool leader = false;
                    FbTeamCheck(ref leader, true);
                    if (leader) {
                        WalkToXy(now.PanQQ, "四绝庄");
                        Thread.Sleep(1000);
                        Monster pan = new Monster();
                        if (GetNpc(SiJueResource.PanQQ, ref pan)) {

                            if (now.Index == SiJueHuanIndex.Fourth) {
                                if (TalkNpc(pan.ID, SiJueHuan.FourStartMsg1)) {
                                    Thread.Sleep(1000);
                                }
                                if (TalkNpc(pan.ID, SiJueHuan.FourStartMsg2)) {
                                    Thread.Sleep(500);
                                    WalkToXy(shouldStand, "四绝庄");
                                    Thread.Sleep(1000);
                                    start = true;
                                    HorseOperate(false);
                                }
                                continue;
                            }


                            if (TalkNpc(pan.ID, SiJueHuan.StartMsg)) {
                                Thread.Sleep(500);
                                WalkToXy(shouldStand, "四绝庄");
                                Thread.Sleep(1000);
                                start = true;
                                HorseOperate(false);
                            }
                        }
                    }
                    else if (shouldStand.HowFar(TheGamer.JsXY) > 2f) {
                        WalkToXy(shouldStand, "四绝庄");
                        Thread.Sleep(1000);
                        HorseOperate(false);
                    }
                    continue;
                }


                if (_fbPause)
                    _fbPause = Conf.SiJueFirstAttack.Value ?
                        false :
                        (mlist.Count(t => t.Type == 3 && t.Flag > 12 && t.HP > 0 && t.HP < 1) == 0);

                //进行数据分类
                noMonsterCounter = (mlist.Count(t => t.Type == 3 && t.Flag > 12 && t.HP > 0) == 0) ? noMonsterCounter + 1 : 0;

                switch (now.Index) {
                    case SiJueHuanIndex.First:
                        DealXianJin(mlist, now);
                        KillXiaoGuai(mlist, now);
                        break;
                    case SiJueHuanIndex.Second:
                        if (!DealHuiYinFan(mlist, now))
                            LocationStay(mlist, now);
                        break;
                    case SiJueHuanIndex.Third:
                        KillXiaoGuai(mlist, now);
                        break;
                    case SiJueHuanIndex.Fourth:
                        if (!DealLongZhu(mlist)) {
                            KillXiaoGuai(mlist, now);
                            DealXianJin(mlist, now);
                        }
                        break;
                }

                if (noMonsterCounter < 180 && mlist.Count(t => t.Type == 3 && t.Flag == 10 && t.Name == now.BossName) > 0)
                    noMonsterCounter = 181;

                if (noMonsterCounter > 150 && TheGamer.JsStaticCounter > 20) {
                    Walk(now.Center);
                    Thread.Sleep(1000);
                }

                if (noMonsterCounter > 50) {
                    noBag = true;
                    var bags = mlist.Where(t => t.IsBag);
                    foreach (var bag in bags) {
                        WalkToXy(bag.MonXy, "四绝庄");
                        Thread.Sleep(1000);
                        Catch(bag.ID);
                        noBag = false;
                        noMonsterCounter = 200;
                        Thread.Sleep(1000);
                        Drop();
                        //由于出现了捡物+没有怪存在 所以表示这个Boss已经刷完了
                    }
                }

                if (start && noBag && noMonsterCounter > 200) {
                    WalkToXy(now.PanQQ, "四绝庄");
                    Thread.Sleep(1000);
                    Monster pan = new Monster();
                    if (GetNpc(SiJueResource.PanQQ, ref pan)) {
                        if (TalkNpc(pan.ID, now.ChuanSongToNextMsg)) {
                            Thread.Sleep(2000);
                            if (TheGamer.JsXY.HowFar(pan.MonXy) > 5f) {
                                start = false;
                                _fbPause = true;
                                var next = now.NextHuan;
                                now = next;
                                shouldStand = GetHuanStartXY(now);
                            }
                        }
                    }
                }
            }
            Controler.FKControler = false;
        }

        /// <summary>
        /// 取当前环节初始化站位
        /// </summary>
        /// <param name="huan"></param>
        /// <returns></returns>
        private XY GetHuanStartXY(SiJueHuan huan) {
            var stand = new XY();
            List<TeamMember> tlist = new List<TeamMember>();
            TeamView(ref tlist);
            int ti = tlist.FirstOrDefault(t => t.Name == PermaName).Index;
            switch (huan.Index) {
                case SiJueHuanIndex.First:
                    stand.X = huan.Center.X + (float)Math.Sin(Math.PI * (double)ti / 3.0) * 6f;
                    stand.Y = huan.Center.Y + (float)Math.Cos(Math.PI * (double)ti / 3.0) * 6f;
                    break;
                case SiJueHuanIndex.Second:
                    stand = new XY(huan.PanQQ.X, huan.PanQQ.Y + 3f);
                    break;
                case SiJueHuanIndex.Third:
                    stand = new XY(94, 41);
                    break;
                default:
                    stand.X = huan.Center.X + (float)Math.Sin(Math.PI * (double)ti / 3.0) * 4f;
                    stand.Y = huan.Center.Y + (float)Math.Cos(Math.PI * (double)ti / 3.0) * 4f;
                    break;
            }
            return stand;
        }

        /// <summary>
        /// 出现龙柱的时候进行的处理
        /// </summary>
        /// <param name="mlist"></param>
        private bool DealLongZhu(List<Monster> mlist) {
            bool hasLongzhu = mlist.Count(t => t.ID > 0 && t.Name != null && t.Name.Contains("龙柱")) > 0;
            var pan = SiJueResource.FourthHuan.PanQQ;
            //存在龙柱
            if (hasLongzhu && TheGamer.JsXY.HowFar(pan) > 5f) {
                PauseKillToDoWork(() => {
                    Walk(pan);
                    Thread.Sleep(800);
                    //SendMessageToUi("龙柱处理");
                });
            }
            return hasLongzhu;
        }

        /// <summary>
        /// 第二环站位保证
        /// </summary>
        /// <param name="mlist"></param>
        /// <param name="huan"></param>
        private void LocationStay(List<Monster> mlist, SiJueHuan huan) {
            if (mlist.Count(t => t.Type == 3 && t.Flag > 12 && t.Name == huan.BossName && t.HP > 0.7) > 0) {
                var stay = new XY(huan.PanQQ.X, huan.PanQQ.Y + 3f);
                if (TheGamer.JsXY.HowFar(stay) > 5f && !TheGamer.Horse) {
                    PauseKillToDoWork(() => {
                        Walk(stay);
                        Thread.Sleep(800);
                        //SendMessageToUi("远程返程");
                    });
                }
            }
        }

        /// <summary>
        /// 处理回音幡
        /// </summary>
        /// <param name="mlist"></param>
        /// <param name="huan"></param>
        /// <returns></returns>
        private bool DealHuiYinFan(List<Monster> mlist, SiJueHuan huan) {
            var hyfs = mlist.Where(t =>
                t.ID > 0 &&
                t.Name == SiJueResource.HuiYinFan &&
                t.Type == 3 &&
                t.Flag == 10).ToList();

            if (hyfs.Count == 0)
                return false;

            foreach (Monster hyf in hyfs) {
                var next = new XY();
                next.X = (hyf.MonXy.X - huan.Center.X > 0f) ? (huan.Center.X - 11f) : (huan.Center.X + 11f);
                next.Y = (hyf.MonXy.Y - huan.Center.Y > 0f) ? (huan.Center.Y - 11f) : (huan.Center.Y + 11f);
                if (TheGamer.JsXY.HowFar(next) > 5f)
                    PauseKillToDoWork(() => {
                        for (int i = 0; i < 4; i++) {
                            if (TheGamer.JsXY.HowFar(next) < 3f)
                                break;
                            Walk(next);
                            Thread.Sleep(800);
                        }
                    });
            }
            return true;
        }

        /// <summary>
        /// 处理小怪
        /// </summary>
        /// <param name="mlist"></param>
        /// <param name="huan"></param>
        private void KillXiaoGuai(List<Monster> mlist, SiJueHuan huan) {

            var mons = mlist.Where(t =>
                    t.ID > 0 &&
                    t.HP > 0.3 &&
                    t.Type == 3 &&
                    t.Flag > 12 &&
                    t.Name != huan.BossName)
                    .OrderBy(t =>
                        t.MonXy.HowFar(TheGamer.JsXY));

            PauseKillToDoWork(() => {
                int counter = 0;
                foreach (var mon in mons) {
                    Skill_JS(TheMenPai.FirstSkill.SkillID, mon.ID);
                    Thread.Sleep(700);
                    if (counter++ > 3)
                        break;
                }
            });
            Thread.Sleep(500);
        }

        /// <summary>
        /// 躲避陷阱
        /// </summary>
        /// <param name="mlist"></param>
        private void DealXianJin(List<Monster> mlist, SiJueHuan huan) {
            var xians = mlist.Where(t => t.ID > 0 && !t.IsBag && t.Type == 7 && string.IsNullOrWhiteSpace(t.Name)).ToList();
            if (xians.Count == 0)
                return;
            var r = new Random();
            var next = TheGamer.JsXY;
            var error = 0;
            if (xians.Count(t => t.MonXy.HowFar(TheGamer.JsXY) < 5f) > 0) {
            r:
                next.X = huan.Center.X + (float)((int)Math.Sin(Math.PI * (double)r.Next(0, 360) / 180.0) * 7);
                next.Y = huan.Center.Y + (float)((int)Math.Cos(Math.PI * (double)r.Next(0, 360) / 180.0) * 7);
                if (xians.Count(t => t.MonXy.HowFar(next) < 5f) > 0 || next.HowFar(huan.Center) > 10f) {
                    if (error++ > 30)
                        return;
                    goto r;
                }
            }
            //SendMessageToUi("陷阱走位");
            PauseKillToDoWork(() => {
                for (int i = 0; i < 2; i++) {
                    if (TheGamer.JsXY.HowFar(next) < 3f)
                        break;
                    Walk(next);
                    Thread.Sleep(700);
                }
            });
        }

        /// <summary>
        /// 暂停打怪处理事件
        /// </summary>
        /// <param name="action"></param>
        private void PauseKillToDoWork(Action action) {
            var working = !_fbPause;
            _fbPause = true;
            Thread.Sleep(200);
            action();
            if (working)
                _fbPause = false;
        }

        /// <summary>
        /// 定位当前任务的环节
        /// </summary>
        /// <returns></returns>
        private SiJueHuan FirstLocationHuan() {
            //1.使用角色坐标进行初始化定位
            var list = new List<SiJueHuan>{
                SiJueResource.FirstHuan,
                SiJueResource.SecondHuan,
                SiJueResource.ThirdHuan,
                SiJueResource.FourthHuan,
            };

            //假设离他最近的NPC所在的环为当前环
            var think = list.OrderBy(t => t.PanQQ.HowFar(TheGamer.JsXY)).ToList()[0];
            SiJueHuan result;
            if (CheckThinkHuan(think, out result)) { return result; }
            if (think.NextHuan != null) { if (CheckThinkHuan(think.ForeHuan, out result)) { return result; } }
            if (think.ForeHuan != null) { if (CheckThinkHuan(think.ForeHuan, out result)) { return result; } }
            SendMessageToUi("error__无法确定当前的环节信息");
            return list.First(t => t != think && t != think.ForeHuan && t != think.NextHuan);
        }

        /// <summary>
        /// 检查初级判断的环节是否是正确的环节
        /// </summary>
        /// <param name="huan"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        private bool CheckThinkHuan(SiJueHuan huan, out SiJueHuan result) {
            result = huan;
            //尝试走到环节中间点
            if (!TryWalkToHuanCenter(huan))
                return false;
            //检查Boss是否存在
            if (CheckBossExits(huan))
                return true;
            //通过对话是能够百分之百确定环节的
            result = ConfirmByTalkToPan(huan);
            return true;
        }

        /// <summary>
        /// 通过和潘青青对话来确定当前的环节
        /// </summary>
        /// <param name="huan"></param>
        /// <returns></returns>
        private SiJueHuan ConfirmByTalkToPan(SiJueHuan huan) {
            WalkToXy(huan.PanQQ);
            Thread.Sleep(500);
            Monster pan = null;
            for (int i = 0; i < 30; i++) {
                if (!Controler.SjController)
                    break;
                if (pan != null || GetNpc(SiJueResource.PanQQ, ref pan)) {
                    if (TalkNpc(pan.ID)) {
                        Thread.Sleep(1000);
                        //开始副本
                        #region 等待开启副本对话检查
                        var dia = SiJueHuan.StartMsg;
                        if (NpcDiaCheck(ref dia)) {
                            break;
                        }

                        dia = SiJueHuan.FourStartMsg1;
                        if (NpcDiaCheck(ref dia)) {
                            break;
                        }

                        dia = SiJueHuan.FourStartMsg2;
                        if (NpcDiaCheck(ref dia)) {
                            break;
                        }
                        #endregion

                        var dia1 = SiJueResource.FirstHuan.ChuanSongToNextMsg;
                        var dia2 = SiJueResource.SecondHuan.ChuanSongToNextMsg;
                        var dia3 = SiJueResource.ThirdHuan.ChuanSongToNextMsg;

                        //可以同时传送到123的就是第四次 执行退出
                        if (NpcDiaCheck(ref dia1) &&
                            NpcDiaCheck(ref dia2) &&
                            NpcDiaCheck(ref dia3)) {
                            ChuansongCheck(SiJueResource.FourthHuan, pan);
                            return SiJueResource.FourthHuan;
                        }

                        //可以传送到第三环 -- 返回第三环
                        if (ChuansongCheck(SiJueResource.SecondHuan, pan))
                            return SiJueResource.ThirdHuan;
                        //最远可以传送到2
                        if (ChuansongCheck(SiJueResource.FirstHuan, pan))
                            return SiJueResource.SecondHuan;
                    }
                }
            }
            return huan;
        }

        /// <summary>
        /// 传送信息检查
        /// </summary>
        /// <param name="huan"></param>
        /// <param name="pan"></param>
        /// <returns></returns>
        private bool ChuansongCheck(SiJueHuan huan, Monster pan) {
            var dia = huan.ChuanSongToNextMsg;
            if (NpcDiaCheck(ref dia)) {
                for (int i = 0; i < 5; i++) {
                    TalkNpc(pan.ID, dia);
                    Thread.Sleep(1000);
                    if (!Controler.SjController)
                        break;
                    if (TheGamer.JsXY.HowFar(pan.MonXy) > 3)
                        break;
                }
                return true;
            }
            return false;
        }

        /// <summary>
        /// 尝试走到坐标点
        /// </summary>
        /// <param name="huan"></param>
        /// <returns></returns>
        private bool TryWalkToHuanCenter(SiJueHuan huan) {
            HorseOperate(true);
            Thread.Sleep(1000);
            var start = DateTime.Now;
            while (!CoreClosingControler && Controler.SjController) {
                Thread.Sleep(500);
                if ((DateTime.Now - start).TotalSeconds > 30)
                    return false;
                if (TheGamer.JsXY.HowFar(huan.Center) < 5)
                    return true;
                if (TheGamer.JsStaticCounter > 20) {
                    Walk(huan.Center);
                    Thread.Sleep(1000);
                }
                if (TheGamer.JsStaticCounter > 30)
                    RandomWalk();
            }
            return false;
        }

        /// <summary>
        /// 检查当前位置是否存在BOSS
        /// </summary>
        /// <param name="huan"></param>
        /// <returns></returns>
        private bool CheckBossExits(SiJueHuan huan) {
            var start = DateTime.Now;
            List<Monster> mlist;
            while (!CoreClosingControler && Controler.SjController) {
                Thread.Sleep(500);
                if ((DateTime.Now - start).TotalSeconds > 5)
                    return false;
                if (!View(out mlist))
                    continue;
                //在这里面检索Boss
                if (mlist.Count(t => t.Name == huan.BossName && t.Type == 3 && t.Flag > 12) > 0)
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 四绝庄初始化时候执行敲钟
        /// </summary>
        /// <returns></returns>
        private bool SiJueQiaoZhong() {
            //1.位置判断
            if (TheGamer.JsXY.HowFar(SiJueResource.qzPanQQ) > 8f)
                return false;
            //2.NPC检查

            DateTime start = DateTime.Now;
            bool getYs = false;
            Monster pan = new Monster();
            int error = 0;
            bool isFirstHuan = false;

            while (!CoreClosingControler && Controler.SjController) {
                Thread.Sleep(500);
                if ((DateTime.Now - start).TotalSeconds > 30 || error > 10) { break; }

                if (!getYs) {
                    //检查是否存在这个NPC
                    if (GetNpc(SiJueResource.PanQQ, ref pan)) {
                        //因为找到了这个NPC所以是第一环
                        if (!isFirstHuan)
                            isFirstHuan = true;
                        //近战无宠物隐身
                        if (TheMenPai.IsJinZhan && string.IsNullOrWhiteSpace(TheGamer.PetName)) {
                            WalkToXy(pan.MonXy);
                            Thread.Sleep(500);
                            HorseOperate(false);
                            Thread.Sleep(1000);
                            this.Skill_Common(this.TheMenPai.SpeedSkill.SkillID);
                            if (TalkNpc(pan.ID, SiJueResource.PanQQGetYinshen)) {
                                getYs = true;
                                Thread.Sleep(500);
                            }
                        }
                    }
                }
                else {
                    //走到敲钟的位置
                    WalkToXy(SiJueResource.qzZhong);
                    Thread.Sleep(500);
                    List<Monster> mlist;
                    if (View(out mlist)) {
                        var zhong = mlist.FirstOrDefault(t => t.Type == 3 && t.Name == SiJueResource.SiJueZhong && t.HP > 0.2);
                        if (zhong != null && !string.IsNullOrWhiteSpace(zhong.Name)) {
                            //执行敲钟
                            WalkToXy(zhong.MonXy);
                            Thread.Sleep(500);
                            Skill_JS(TheMenPai.FirstSkill.SkillID, zhong.ID);
                            Thread.Sleep(500);
                        }
                        else { error++; }
                    }
                }
            }
            return isFirstHuan;
        }

        /// <summary>
        /// 四绝庄任务苏州任务处理
        /// </summary>
        private void DoworksInSuZhou() {
            #region 要点说明
            //在苏州存在几种情况
            //1.离Npc太远了
            //2.没有接受任务
            //3.任务已经完成了
            //4.任务已经接受还未开始完成 此时只有队长才有进入副本的权利
            //5.任务已经开始 死亡等操作导致传出了副本 应该是直接进入副本 
            #endregion

            if (TheGamer.JsStaticCounter < 30) {
                Thread.Sleep(1000);
                return;
            }

            if (TheGamer.JsXY.HowFar(SiJueResource.szPanQQ) > 2) {
                WalkToXy(SiJueResource.szPanQQ);
                Thread.Sleep(1000);
                return;
            }

            List<Monster> mlist;
            if (!View(out mlist))
                return;

            var szPan = mlist.FirstOrDefault(t => t.Type == 3 && t.Name == SiJueResource.PanQQ);
            if (szPan == null || string.IsNullOrWhiteSpace(szPan.Name))
                return;

            if (TalkNpc(szPan.ID, SiJueResource.szPanQQSiJueZhuangEnYuan)) {
                Thread.Sleep(2000);
                var checkMsg = SiJueResource.szPanQQJinRuFuBen;
                //检查是否已经接受了任务
                if (NpcDiaCheck(checkMsg)) {
                    //接受了任务 进行进入副本操作
                    TalkNpc(checkMsg);
                    for (int i = 0; i < 100; i++) {
                        Thread.Sleep(300);
                        if (TheGamer.MapName != "苏州")
                            break;
                        if (!Controler.SjController || CoreClosingControler)
                            break;
                    }
                }
                else {
                    MessionState mState = MessionState.未知;
                    AcceptOrFinish(ref mState);
                    if (mState == MessionState.需要接受)
                        Thread.Sleep(2000);
                    if (mState == MessionState.未知)
                        Thread.Sleep(5000);
                }
            }
        }

        /// <summary>
        /// 判断角色是否在某张地图
        /// </summary>
        /// <param name="map"></param>
        /// <returns></returns>
        private bool AreYouThere(string map) {
            return TheGamer.MapName == map;
        }
        #endregion

        #region 自动摆摊

        //9			7 
        //          y+5
        //21(+12)	12 摆摊
        //60(50)	14 整理
        //140(130)	13 拆分

        //1.能够检测是否掉线了
        //2.能够自动重新登录后继续摆摊
        //3.能够自动收摊
        //4.没有东西了自动找人交易

        /// <summary>
        /// 摆摊线程
        /// </summary>
        private void Baitan() {
            Controler.BaitanController = true;
            var error = 0;
            while (Controler.BaitanController && !CoreClosingControler) {
                Thread.Sleep(200);
                if (TheGamer.MapName == BaitanConf.Map) {
                    if (TheGamer.JsXY.HowFar(BaitanConf.BaitanLocation) < 2) {
                        HorseOperate(false);
                        Thread.Sleep(1000);
                        #region 执行摆摊
                        ZhengliBag();
                        Thread.Sleep(1000);
                        if (UseButton("背包按钮集", "bbbbbb-02ffff|fdeb78-1fffff", 12, 5)) {
                            UseButton("确定", "fdeb78-1fffff", 5, 5);
                            UseButton("关闭珍兽交易", "fdeb78-1fffff", 52, 5);
                            if (error++ > 20) {
                                Controler.BaitanController = false;
                            }
                            if (TheGamer.State == 10) {
                                foreach (var t in BaitanConf.PriceMap) {
                                    Sell(t.Key, t.Value);
                                }
                                Controler.BaitanController = false;
                                SendMessageToUi("摆摊完成");
                            }
                        }
                        #endregion
                    }
                    else {
                        WalkToXy(BaitanConf.BaitanLocation);
                    }
                }
                else {
                    Walk(BaitanConf.Map);
                }
            }
        }

        /// <summary>
        /// 整理包裹
        /// </summary>
        private void ZhengliBag() {
            for (int i = 0; i < 2; i++) {
                UseBag(i);
                UseButton("背包按钮集", "bbbbbb-02ffff|fdeb78-1fffff", 50, 5);
            }
        }

        /// <summary>
        /// 收摊
        /// </summary>
        private void ShouTan() {
            UseBag(0);
            UseButton("背包按钮集", "bbbbbb-02ffff|fdeb78-1fffff", 12, 5);
            UseButton("收摊", "fdeb78-1fffff", 100, 5);
            UseButton("确定", "fdeb78-1fffff", 5, 5);
            UseButton("确定", "fdeb78-1fffff", 5, 5);
            //完成之后执行test
            Thread.Sleep(300);
            var tx = TheGamer.JsXY;
            for (int i = 0; i < 5; i++) {
                RandomWalk();
                Thread.Sleep(500);
                if (TheGamer.JsXY != tx) {
                    SendMessageToUi("完成收摊了~！");
                    break;
                }
            }
        }

        /// <summary>
        /// 通过序号来定位使用的包裹栏
        /// </summary>
        /// <param name="idx"></param>
        private void UseBag(int idx) {
            UseBag(new List<int>() { idx * 30 }, true);
        }

        //整合交易模式：
        //1.每次采集之前将身上的金币整数部分存入银行
        //2.如果身上具有10组或以上的材料就会执行摆摊
        //3.作物成熟之后执行收摊

        /// <summary>
        /// 出售物品
        /// </summary>
        /// <param name="bagName">武平名字</param>
        /// <param name="price">价格</param>
        /// <param name="start">开始背包序号</param>
        /// <param name="end">结束背包序号</param>
        /// <param name="isfullName">物品名使用的全名称还是需要进一步查询的名字</param>
        private void Sell(string bagName, string price, int start = 0, int end = 80, bool isfullName = true) {
            List<GamerBag> baglist;
            ViewMyBag(out baglist, start, end);
            var idList = new List<int>();
            foreach (var bag in baglist) {
                if (!Controler.BaitanController || CoreClosingControler)
                    return;
                if ((isfullName && bag.Name == bagName) || (!isfullName && bag.Name.Contains(bagName))) {
                    //SendMessageToUi("出售[{0}|{1}]({2})", bag.ID, bag.Name, price);
                    UseBag(new List<int>() { bag.ID });
                    if (UseButton("上架商品", "bbbbbb-02ffff|fdeb78-1fffff", 5, 5)) {
                        dm.SendString(gameHwnd, price);
                        UseButton("上架商品", "bbbbbb-02ffff|fdeb78-1fffff", 5, 5);
                    }
                }
            }
        }

        /// <summary>
        /// 设置摆摊的位置
        /// </summary>
        public void SetBaitanLocation() {
            this.BaitanConf.SetLocation(TheGamer.MapName, TheGamer.JsXY);
        }


        /// <summary>
        /// 通过识图来使用按钮
        /// </summary>
        /// <param name="sign">图像识别文字</param>
        /// <param name="color">图像识别颜色信息</param>
        /// <param name="extraX">与识别图像的坐标x偏移量</param>
        /// <param name="extraY">与识别图像的坐标y偏移量</param>
        /// <param name="x1">图像识别开始坐标x</param>
        /// <param name="y1">体香识别开始坐标y</param>
        /// <param name="x2">图像识别结束位置x</param>
        /// <param name="y2">图像是被结束位置y</param>
        /// <returns></returns>
        private bool UseButton(string sign, string color, int extraX, int extraY, int x1 = 0, int y1 = 0, int x2 = 2000, int y2 = 2000) {
            int x, y;
            dm.DmClick(40, 40, 2);
            for (int i = 0; i < 10; i++) {
                if (dm.DmRcWord(sign, color, out x, out y, x1, y1, x2, y2)) {
                    dm.DmClick(x + extraX, y + extraY, 2);
                    Thread.Sleep(500);
                    return true;
                }
                Thread.Sleep(300);
            }
            return false;
        }
        #endregion

        #region 帮会宝盆

        /// <summary>
        /// Npc对话
        /// </summary>
        /// <param name="npcName"></param>
        /// <param name="dias"></param>
        /// <returns></returns>
        private bool TalkNpc(string npcName, params string[] dias) {
            var npc = new Monster();
            if (GetNpc(npcName, ref npc)) {
                WalkToXy(npc.MonXy);
                var first = false;
                bool br;
                //对话信息
                foreach (var dia in dias) {
                    if (!first) {
                        //第一个对话表示初次打开
                        first = true;
                        br = TalkNpc(npc.ID, dia);
                    }
                    else {
                        br = TalkNpc(dia);
                    }
                    if (br) {
                        Thread.Sleep(1000);
                    }
                    else {
                        return br;
                    }
                }
                return true;
            }
            return false;
        }


        /// <summary>
        /// 帮会聚宝盆状态枚举
        /// </summary>
        private enum BaoPenWorkingState
        {
            CaiKuang,
            TouKuang
        }
        /// <summary>
        /// 聚宝盆线程
        /// </summary>
        private void BaoPen() {

            WorkStateShow(GameState.宝盆);

            //标记工作状态
            var st = BaoPenWorkingState.CaiKuang;
            Controler.BaoPenController = true;

            var pen = new XY(99, 81);
            var kuang = new XY(100, 144);

            var ck = 0xc22;//采矿技能id
            var tk = 0xc23;//投矿id

            var p = kuang;
            var s = ck;

            var start = DateTime.Now;
            while (Controler.BaoPenController) {

                //直接结束
                if (CoreClosingControler) {
                    return;
                }

                if ((DateTime.Now - start).TotalMinutes > 15) {
                    break;
                }

                Thread.Sleep(200);

                //位置移动
                if (TheGamer.JsXY.HowFar(p) > 2) {
                    if (TheGamer.JsStaticCounter > 2) {
                        Walk(p);
                        Thread.Sleep(500);
                    }
                }

                //采矿或者投矿
                if (TheGamer.JsXY.HowFar(p) < 2) {
                    if (TheGamer.JsStaticCounter > 3) {
                        for (int i = 0; i < 15; i++) {
                            Thread.Sleep(200);
                            //最好的状态是发现采集状态
                            if (i % 5 == 0) {
                                Skill_JS(s);
                                Thread.Sleep(500);
                            }
                            if (TheGamer.JsStaticCounter < 3) {
                                //如果使用了成功使用了技能:则转换到下一个动作
                                if (TheGamer.JsXY.HowFar(p) < 2) {
                                    switch (st) {
                                        case BaoPenWorkingState.CaiKuang:
                                            p = pen;
                                            s = tk;
                                            st = BaoPenWorkingState.TouKuang;
                                            break;
                                        default:
                                            p = kuang;
                                            s = ck;
                                            st = BaoPenWorkingState.CaiKuang;
                                            break;
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
            }

            if (Controler.BaoPenController) {
                WalkToXy(pen);
                //领取
                //var npc = new Monster();
                for (var i = 0; i < 10; i++) {
                    if (CoreClosingControler) {
                        break;
                    }
                    Thread.Sleep(1000);
                    if (TalkNpc("镶玉聚宝盆", "BHCJ_140523_34", "BHCJ_140523_180")) {
                        break;
                    }

                    //if (GetNpc("镶玉聚宝盆", ref npc)) {
                    //    if (TalkNpc(npc.ID, "BHCJ_140523_34")) {
                    //        Thread.Sleep(2000);
                    //        if (TalkNpc("BHCJ_140523_180")) {
                    //            break;
                    //        }
                    //    }
                    //}
                }
            }

            WorkStateShow(GameState.空闲);

        }
        #endregion

        #region 自动令牌系统

        /// <summary>
        /// 楼兰令牌
        /// </summary>
        private void LoulanLinPai() {
            var st = DateTime.Now;
            Config<int> week = new Config<int>("linPai", this.PermaName + "/week", MuYue.Common.Utility.GetWeek(st));
            Config<int> count = new Config<int>("linPai", this.PermaName + "/count", 0);
            //充值统计信息
            if (week.Value != MuYue.Common.Utility.GetWeek(st)) {
                count.Value = 0;
                week.Value = MuYue.Common.Utility.GetWeek(st);
            }

            count.Value = 0;
            if (count.Value > 5) {
                SendMessageToUi("本周任务数上限了!!");
                return;
            }

            WorkStateShow(GameState.幻境);

            Controler.LoulanLinPaiController = true;

            var nstart = false; //标记是否开始了
            var firstLoulan = false;

            var fsxy = new XY(170, 120);

            CreateFbKillThread();

            //创建杀怪线程
            while (!CoreClosingControler && Controler.LoulanLinPaiController) {
                Thread.Sleep(200);
                if (TheGamer.MapName == "楼兰") {
                    if (TheGamer.JsXY.HowFar(fsxy) > 2) {
                        WalkToXy(fsxy);
                        continue;
                    }

                    if (!firstLoulan) {
                        firstLoulan = true;
                        st = DateTime.Now;
                    }
                    else if ((DateTime.Now - st).TotalMinutes > 3 || count.Value > 5) {
                        //冻结双倍 然后退出
                        FrozenDouble();
                        Controler.LoulanLinPaiController = false;
                    }
                    else {

                        var npc = new Monster();
                        if (GetNpc("浮生", ref npc)) {
                            //#{TLHJ_120110_01}
                            //#{TLHJ_120110_02} 进入副本
                            //#{TLHJ_120110_03} 次数查询
                            //#{TLHJ_120110_62} 接受任务
                            //#{TLHJ_120110_04}
                            if (TalkNpc(npc.ID, "TLHJ_120110_62")) {
                                var state = MessionState.未知;
                                Thread.Sleep(2000);
                                AcceptOrFinish(ref state);
                                Console.WriteLine(state);
                            }
                            Thread.Sleep(1000);
                            if (TalkNpc(npc.ID, "TLHJ_120110_02")) {
                                Thread.Sleep(5000);
                            }
                            nstart = false;
                        }
                        //执行接任务交任务然后进副本的循环操作
                    }
                }
                else {
                    if (firstLoulan)
                        firstLoulan = false;
                    if (TheGamer.MapName == "天龙幻境") {
                        if (!nstart) {
                            var leader = false;
                            if (FbTeamCheck(ref leader, true)) {
                                if (leader) {
                                    WalkToXy(65, 59);
                                    var npc = new Monster();
                                    if (GetNpc("若梦", ref npc)) {

                                        #region MyRegion
                                        //#{TLHJ_120110_28}
                                        //#{TLHJ_120110_29} //召唤
                                        //#{TLHJ_120110_30} 退出
                                        //#{TLHJ_120110_04} 介绍

                                        //#{TLHJ_120110_33}
                                        //#{TLHJ_120110_34}
                                        //#{TLHJ_120110_35}

                                        //#{TLHJ_120110_31}
                                        //#{INTERFACE_XML_557} 确定???
                                        //#{INTERFACE_XML_542} 
                                        #endregion

                                        if (TalkNpc(npc.ID, "TLHJ_120110_29")) {
                                            Thread.Sleep(1000);
                                            if (TalkNpc("TLHJ_120110_34")) {
                                                nstart = true;
                                                count.Value++;
                                            }
                                        }
                                    }
                                }
                                else {
                                    List<Monster> mlist;
                                    if (View(out mlist)) {
                                        if (mlist.Count(temMon => temMon.Type == 3 && temMon.Flag > 12) > 0) {
                                            nstart = true;
                                            count.Value++;//记录时间进行记录优化
                                        }
                                    }
                                }
                            }
                        }
                        if (TheGamer.Horse) {
                            HorseOperate(false);
                            Thread.Sleep(1000);
                        }
                        Thread.Sleep(500);
                        //else if (nover) {
                        //    if (TheGamer.JsStaticCounter > 30) {
                        //        //退出副本
                        //    }
                        //}
                    }
                    else {
                        Walk("楼兰");
                    }
                }
                //循环结束之后退出杀怪线程
            }
            Controler.FKControler = false;
            WorkStateShow(GameState.空闲);
        }

        private void CreateFbKillThread(bool fbPause = false) {
            _fbPause = fbPause;
            new Task(FbKillThread).Start();
        }


        public void TestMethod() {

        }


        /// <summary>
        /// 冻结双倍经验
        /// </summary>
        private void FrozenDouble() {
            var npcxy = new XY(154, 121);
            if (TheGamer.MapName == "楼兰") {
                var err = 0;
                //控制器
                while (Controler.LoulanLinPaiController && !CoreClosingControler) {
                    Thread.Sleep(500);
                    if (TheGamer.JsXY.HowFar(npcxy) < 2) {
                        var npc = new Monster();
                        if (GetNpc("格鲁尔", ref npc)) {
                            TalkNpc(npc.ID, "SBSJ_100726_01");
                            Thread.Sleep(1000);
                            if (ConfirmBtnDeal()) {
                                break;
                            }
                            err++;
                        }
                    }
                    else {
                        WalkToXy(npcxy);
                    }
                    if (err > 10) {
                        break;
                    }
                }
            }
        }


        #endregion

        #region 数据测试专用
        internal void TestTeamData() {
            var team = new List<TeamMember>();
            this.TeamView(ref  team);
            foreach (var m in team) {
                Console.WriteLine("id:{0} name:{1} hp:{2} index:{3} position({4},{5})", m.ID, m.Name, m.HP, m.Index, m.NwXY.X, m.NwXY.Y);
            }
        }
        #endregion
    }
}